Vlang - Go done right

2023-02-13

When you take the simplicity and ease-of-use of Go, add in properties and immutability-by-default of Rust, and compile it to human readable C to leverage pre-existing C toolchains, you begin to approach what Vlang is. Vlang makes difficult tasks simple and elegant, compiles fast during testing, runs fast during prod, and is a joy to work with!

Vlang was first publicly released in 2019 by Alexander Medvednikov. V programs are generally compiled down to C, then compiled using a C compiler to binary. So anyplace C can run, V can also run. This is nothing new, but isn’t very common anymore. People and organizations have recently tended to target LLVM or to create binaries on their own, but being able to take advantage of C’s now over 50 years of tooling and optimizations and standardization is a smart move.

Installing V is simple. Merely:

git clone https://github.com/vlang/v
cd v
make

And if you want to make V available system-wide:

sudo ./v symlink

Now let’s do a fun test. Using this method allows us to see more of a language’s syntax and design decisions. We will test whether a series of brackets are balanced.

fn main() {
    brackets := ['','[]','[][]','[[][]]','][','][][','[]][[]','[][[][[]][][[][]]]']
    for b in brackets {
        println("$b: ${test_balanced(b)}")
    }
}

fn test_balanced(s string) bool{
    mut open := 0
    for c in s {
        match c {
           `[`{ open++ }
           `]`{
                if open == 0 {
                    return false
                }
                open--
            }
            else{ return false }
        }
    }
    return open == 0
}

Right off we can see a for loop, a match statement, printlns, function declarations, and if/else statements. A fine start! We also see a little bit of the difference between quotation marks (") and backticks (`).

for loops are fairly clear, almost exactly the same as in Go, but there are multiple ways to do them.

match statements are like a standard switch statement, but also has some extra features, most notably range matching.

Slightly different from C, backticks are used for u8 literals, and quotation marks (’ or “) are strings.

Look at mut open := 0. By default V variable declarations are immutable, so if we want them to change within a given context we must declare it as mut, short for ‘mutable’. We want open to increment or decrement so we declare it with mut. Also note that we didn’t declare what the type was. We could enforce a certain type and that would look like mut open := int(0). int is the default but we have multiple options.