Tutorials

_images/v.png

Index vlang.io

In the beginning

V programming, like almost all other, starts with source code in a textual form. This is the root form and programmer representation of the instructions intended for computation.

A V programmer needs an Operating System and base of development. GNU/Linux is assumed throughout this docset, but V is cross-platform and certain abstractions allow discussing V with little difference in the conceptual reasoning regarding software development. This docset also assumes a desktop operating environment, with a graphical interface containing a terminal emulator.

Next up in the required tools is a shell to provide the human machine input output interface. This document and listed V programs were entered into the computer with:

  • Xubuntu GNU/Linux

  • XFCE Desktop

  • Konsole terminal emulator

  • GNU Bash

  • Vim text editor

These make up the base of the V development environment here.

You have a wide set of options to suit wants, requirements, and preferences when it comes to this base:

  • You may want to use Windows or MacOS, or other system for the OS.

  • There are dozens of desktop environments, GNOME, KDE, Cortana, Windows, more

  • There are hundreds of terminal emulators to choose from

  • There are thousands of text editors to choose from

  • There are Interactive Development Environments, out the yin-yang.

Note: One point, with the choice of editor. V programming starts with text files, not What You See Is What You Get document processor files like LibreOffice Writer or Microsoft Word uses by default. Source programs need to be saved as text, not .doc.

Given that base, most reasoning and work with V programming resolves to a common point of concepts for discussion. The conceptual statement “edit a text file”, does not depend on operating environment. The details vary, but the concept is shared.

Using a command line is another concept that is shared across environments, and we use this commonality in the most of the tutorials to follow.

This author prefers console mode text editing, in Vim. Many others prefer a more visually oriented IDEish code editors like VSCodium, https://vscodium.com/

Marketing blurb, preference opinion spread: I think, therefore V I am. Write your code in Vim.

With those base tools in place, V programmers will need a few other utilities. Utilities is likely not the best terminology to use here. Other programs and program suites might be more appropriate. git is one such tool that is required to get started with V programs. Mainly to get the source code that bootstraps an initial V, that then builds V in V.

This author uses Fossil SCM for revision control, using Git and the git command when required, not by first choice for source code repository management. git is good, GitHub makes it globally ubiquitous. Fossil SCM is more all in to start, and is designed for self hosting and developer independence, which is a personal preference.

Beginner

Tutorial 1, POST

Tutorial one. Verification that there is at least a minimally functional installation of V.

POST

Power On Self Test. This part of the tutorials is not really a power on test, but a post installation test, but no one but the author would know what was meant if PIT was used as the acronym.

And to set the tone as to expectations of base skill level:

Open a terminal, create a working directory, change into it, and edit a new file, tutorial1.v.

This tutorial assumes a base level of getting to work as programmer. How to get into a command console and type the words and symbols that make the programs.

In tutorial1.v, add the text:

println("Hello, world")

Save and exit the editor back to the command console. Let’s try things:

prompt$ v run hello.v

If things are properly installed and working, after a very short period of time, the v compiler tool will produce:

Hello, world

This means the V compiler, the V libraries, and other pre-requisites are functional. println is a vlib function that is builtin and available to all V programs. vlib is the V standard library. One of the modules, builtin includes a small core of functions that are always available.

If the program does not display the Hello message, then the base installations are not yet ready for V development. You will need to look through the information at

https://github.com/vlang/v/blob/master/doc/docs.md#install-from-source

If it does work as expected, time to check the code into a repository:

prompt$ fossil add tutorial1.v
prompt$ fossil ci -m "Starting in on some V tutorials"

With that done, you can update tutorial1.v to experiment with other messages and you’ll always be able to go back to the original, or at least have it as a historical reference point in your personalized V programming tutorial experiences.

Get used to Revision Control with your source code. Keep the V motto in mind: For developing maintainable software. Even source code meant for one use, make it and store it with tools that allows for future maintenance and personal (or public) reference.

Tutorial 2

A real program, but still a simple message.

// V Programming, tutorial 2
module main
import os

// Starts here.  vdoc can use this comment for API documentation
pub fn main() {
    print("Name? ")
    mut name := os.get_line()
    println("Hello, ${name}.  Looks like you are using V.  Nice.")
}

Unlike most of the listings shown in V Programming, the tutorial listings may not have a quick download link attached. These tutorials are meant to be learnt the hard way. Type it in.

prompt$ v run listings/tutorial2.v
Name? Blue
Hello, Blue.  Looks like you are using V.  Nice.

This code puts the code in a main module. This is important. The default entry point for V programs, based on common conventions between Operating Systems and programming languages, is main. The V main function expects to be in a main module.

Then there is an import of the os module. This provides access to a function to retrieve a string from standard input, os.get_line().

The code then defines a pub fn main. Aside: I pronounce that with pub ryhming with tub, and fn expanded to fun for the mind’s inner dialog and when speaking.

In this function is a few code lines.

A call to the builtin print function, displaying a prompt without a newline, leaving the cursor on the same line.

A variable definition mut name, a mutable variable called “name”. It is initialized by calling the os module function get_line. The return type of get_line is string. This is enough for the V type inference engine to know that “name” is a string variable, a mutable string variable.

Then there is an invocation of the builtin println function, with a twist.

There is a ${name} variable interpolation used in the displayed message output. This replaces whatever the program operator entered as data for the get_line function. Techincal detail: The squiggly brace uses around name are optional. They are used to delimit the identifier from any possible surrounding text that is abut to the identifier name without any white space.

get_line reads a single “line” of data from standard input, which needs to be terminated by a new line character sequence (usually from the keyboard) or an end of file condition.

interpolation sidetrip

Interpolation

a message (spoken or written) that is introduced or inserted

String interpolation is a handy feature of V. Variable names, structure properties, or entire expressions of indefinite complexity can be replaced with ${expr} inside a V string literal.

bracing sidetrip

V includes both statements (like variable definitions) and expressions, which can be included in statements. V does not require any special markers between statements. Most languages with a ancestry influenced by C, use semi-colons as a statement delimiter; a mandatory statement delimiter. V does not require, nor allow statement separators (except in the C like format of the for statement, but that is a special case of semi-colon use in V).

What V does inherit from C syntax, is the use of { and } braces to group statements. V counts as a brace language, but does not count as a semi-colon programming language.

Expressions are a component of most statements. V is close, but does not allow statements as expressions in all cases. For instance, the definition and initialization of a variable cannot be used inside an encompassing expression. Very sophisticated expressions can be used in an assignment statement, but expressions can’t include “statements”. The V lexical scanner and semantic parser takes care of determining separation of statements. There is no error prone[1] automatic semi-colon insertion that is used in some languages. Looking at you, JavaScript.

Back to the tutorial exercises.

Now is a good time to ensure you’ve saved your code in a repository.

Not only are source code repositories an on-site backup of source code, but also situational awareness tools that help tracking changes made.

prompt$ fossil add tutorial2.v
prompt$ fossil commit -m "A second V tutorial completed"

Tutorial 3

Modules. While V is designed to allow for very informal programs, statements evaluated from a top level, it is best suited for modular programming with collections of functions inside importable modules. Back in tutorial 1, the entire program was a single statement to print out a message.

Tutorial 2 included a little more of the paperwork that comes with almost all programming environments. Placing things in named spaces and other source code to manage the bridge from black-box tool to the inner details of how programs and are pieced together. With V, building up applications is at a fairly high level. Import various components to deal with the computing behind the domain problem space, and less with the programming details of things like data structure manipulation. V is also a systems language, and writing components as modules, can be very low level nit picky programming. Abstraction potential in V covers a very wide band. These initial tutorial samples will mostly be high level programming, with a lot of details hidden behind simple module imports.

Let’s start in on a module. A tutorial module. We have seen module main. module main is where V expects to find the main function, which is the default entry point from the C ABI point of view. Some operating systems use a different set of default names, but this docset focuses on the POSIX definitions. We’ll create a module tutorial and import it into a main module as we build up the program.

// A tutorial module, in V
module tutorial

// Public function accepting a string and returning an integer
pub fn tutorial3(msg string) int {
    println("VP tutorial 3")
    println(msg)
    return msg.len
}

Like a lot of high level V code, there is not a lot of source code required to do some pretty amazing things. This sample isn’t that amazing, but, you know, cheer leading works better when it’s positive cheer leading.

You can have lots of source files that group code and data into a single module, but there can only be one module per source file. Trying to v run this example won’t work, as there is no main entry point. There are ways, which will come up later, but for now this is simply an importable module, designed to be used as an import.

Another source file is required. Let’s call this one tut3main.v

// Running tutorial 3
module main
import tutorial

pub fn main() {
    rv := tutorial.tutorial3("A tutorial message")
    println("Return value from tutorial3 invocation was: ${rv}")
}

And now to run things. tut3main will import tutorial3 so all we need to do is:

prompt$ v run tut3main.v

And we get:

A tutorial message
Return value from tutorial3 invocation was: 18

The message, and a return value which is the length of that message.

Soon, we see the V way of organizing modules and application level imports.

For now, let’s go over some of the things that just happened.

A module is a code container, a named item that can include all kinds of data and code. V import works by looking through a search path for V files that match the import name. In this case the tutorial module.

TODO


V, programming with potential

Index | Previous: Onboarding | Next: License