V Introduction

by "Blag" - Senior Developer Evangelist

Return to Geeky Thursday

What is V?


V is a compiled language.


Open-Sourced on 2019.


Influenced by Go and Rust.


Small, easy to learn but extremely fast, versatile and fun.


How to install V


Simply clone it and build it


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

cd v

make


Want to update it?


v up

Who uses V?


Here are some nice projects build using V


  • V - Yep...V is build on V
  • Volt - Desktop client for Slack, Gmail, Twitter and many more...
  • Vid - Sublime Text style editor
  • Vorum - Blogging/Forum platform

Starting out...


There's a web playground here

I prefer to simply use an editor and compile/run the code

Comments


Comments are very simple

				
fn main(){
	
    //This is a comment


    /*This is 

    a comment as well*/
    
}
				

Printing Output


				
fn main(){
	
    println("Hello World")

    println(5)

}
				

Variables


Variables don't need a type, and they are immutable by default


:= is used to initialize a variable while = is used to update its value (if we make them mutable)


There are no global variables


				
fn main(){
	
    my_var := "I cannot change this"
    
    mut another_var := "I can change this"
    
    another_var = "Changed"	
	
}					
				

Conditionals


The good IF-ELSE always prevail

				
fn main() {
	
    a := 3
    
    if a > 0 {
		
        println("$a is bigger than zero")
        
    } else {
		
        print("$a is way to small")
        
    }
    
} 
				

Match is a good way to have an IF-ELSE

				
fn main() {
	
    a := "3"
    
    match a {
		
       '1' { println('One') }
       
       '2' { println('Two') }
       
       '3' { println('Three') }
       
       else { println('Out of range') }
       
    }
    
} 
				

Loops

We only have the FOR loop but it can be used in many ways...

				
fn main() {
	
    for i := 0; i < 6; i++{
		
        println(i)
        
    }
    
} 
				

				
fn main() {
	
    a := [1,2,3,4,5]
    
    for i in a{
		
        println(i)
        
    }
    
} 
				

				
fn main() {
	
    mut i := 0
    
    for i < 5{
		
        println(i)
        
        i++
        
    }
    
} 
				

Functions


Method can return one, multiple or no values

				
fn say_greetings(name string) string{
	
    greet := "Hello " + name
    
    return greet
    
} 


fn main() {
	
    println(say_greetings("Blag"))
    
} 
				

				
fn sum_by(a int, b int) (int, int){
	
    return a + b, a * b
    
} 

fn main() {
	
    a, b := sum_by(2,5)
    
    println("$a, $b")
    
} 
				

				
fn greet(name string){
	
    println("Hello $name")
    
} 


fn main() {
	
    greet("Blag")
    
} 
				

Arrays and Maps


				
fn main(){
	
    a := [1,2,3]

    println(a[0])
    
}
				

				
fn main(){
	
    mut names := ["Blag"]
    
    names << "Oliver"
    
    println(names.len)
    
}			
				

				
fn main(){
	
    mut m := map[string]int
    
    m['one'] = 1
    
    m['two'] = 2
    
    
    println(m['two'])
    

    numbers := {
		
        'one': 1,
        
        'two': 2
	
    }
    
}
				

Structs


Structs are created on the stack, but with & they can be on the heap

				
struct Names {
	
    a string
    
    b string
    
}


fn main(){
	
    name := Names{
		
        a: "Blag"
	
        b: "Oliver"
	
    }
    

    println(name.b)
    
}
				

				
struct Names {
	
    a string
    
    b string
    
}


fn main(){
	
    name := &Names{"Blag", "Oliver"}

    println(name.b)
    
}
				

Modules


V is very young but there's already some useful modules

				
import math

import time


fn main(){
	
    println(math.pow(2,8))
    
    println(time.now())
    
}
				

Fibonacci list sequence


Finally...we're going to make our first application...


Create a file and call it fibonacci.v


				
import os


fn main(){
	
    print("Enter a number: ")
    
    num := os.get_line()
    
    println(fib(num.int(), 0, 1))
    
    println(" ")
    
}
				
				
fn fib(num int, a int, b int) string{
	
    mut result := ""
    
    if a > 0 && num > 1{
		
        a_b := a + b
        
        result = result + " " + a_b.str() + 
        
                 fib(num - 1, a + b, a)
        
    }else if a == 0{
		
        a_b := a + b
        
        result = a.str() + " " + b.str() + 
        
                 " " + a_b.str() + 
                 
                 fib(num - 1, a + b, b)
        
    }
    
    return result
    
}
				

To run this just do


v run app.v

This will create an executable and run it...

Making an LCD Number App


This is my favorite application of all time...


Create the app and name it LED_Numbers.v


				
import os


fn main(){
	
    leds := {
		
        '0': [" _  ","| | ","|_| "],
		
        '1': ["  ","| ","| "],
		
        '2': [" _  "," _| ","|_  "],
		
        '3': ["_  ","_| ","_| "],
		
        '4': ["    ","|_| ","  | "],
		
        '5': [" _  ","|_  "," _| "],
		
        '6': [" _  ","|_  ","|_| "],
		
        '7': ["_   "," |  "," |  "],
		
        '8': [" _  ","|_| ","|_| "],
		
        '9': [" _  ","|_| "," _| "]
		
    }
				
				
    print("Enter a number: ")
	
    number := os.get_line()
	
    for i := 0; i < 3; i++{
		
        for num in number {
			
            print(leds[num.str()][i])
			
        }
		
        println("")
		
    }
	
    println("")
	
}
				

When we run it we're going to see...

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


Create the app and name it Decimal_to_Romans.v


				
import os


fn roman_number(number int, keys []int, 

                romans []string) string{
	
    mut result := ""
    
    mut counter := 0
    
    mut num := number
    
    for num > 0{
		
        counter = 0
        
        for key in keys{
			
            if num >= key {
				
                result = result + romans[counter]
                
                num = num - key
                
                break
                
            }
				
				 
            counter++
            
        }
        
    }
    
    return result
    
}


fn main(){
	
    keys := [1000,900,500,400,100,90,50,40,10,9,5,4,1]
    
    romans := ["M","CM","D","CD","C","XC",
    
               "L","XL","X","IX","V","IV","I"]
               
	           
    print("Enter a number: ")
    
    number := os.get_line()
    
    println(roman_number(number.int(), keys, romans))
    
    println("")
    
}
				

When we run it we're going to see...

Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime.


Create the app and name it Random_Names.v


				
import rand

import time


fn main(){
	
    names := ["Anne","Gigi","Blag","Juergen","Marek",
    
              "Ingo","Lars","Julia", "Danielle",
              
              "Rocky","Julien","Uwe","Myles","Mike",
              
              "Steven","Fanny"]
              
			  
    last_names := ["Hardy","Read","Tejada","Schmerder",
    
                   "Kowalkiewicz","Sauerzapf","Karg",
                   
                   "Satsuta","Keene","Ongkowidjojo",
                   
                   "Vayssiere","Kylau","Fenlon",
                   
                   "Flynn","Taylor","Tan"]
				
				
    mut full_names := [""].repeat(100000)
    
	
    rand.seed(time.now().unix)
    
    for i := 0; i < 100000; i++{
		
        full_names[i] = names[rand.next(16)] + " " + 
        
                        last_names[rand.next(16)]
        
    }
    
				   	
}
				

When we run it we're going to see...


I'm impressed...that was really fast -:)

Although I needed to initilize the array with empty values to avoid a memory dump...

Counting Letters


In this example we're going to read a file and count how many time a letter appears...


Name the app Count_Letters.v


Create a file called "readme.txt" with the following text...


"This is a text file that we're going to read using V"


				
import os


fn main(){
	
    line := os.read_file('readme.txt') or{
		
        println('failed to read the file')
        
        return
        
    }


    mut letters := map[string]int
    
    for letter in line.trim_space(){
		
        if letter.str() in letters{
			
            letters[letter.str()] = 
            
            letters[letter.str()] + 1
				
				
        }else{
			
            letters[letter.str()] = 1
            
        }
        
    }
	
	
    for key in letters.keys(){
		
        print('$key --> ')
        
        println(letters[key])
        
    }
    
}
				

When we run it we're going to see...


That's it for now...


V is a pretty cool and fun language


And still on pre-alpha stage!


Easy to learn and amazingly versatile...a language to keep an eye on...


Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...