01
Getting Started
Hello World
println prints with a newline.
vlang
fn main() {
println("Hello, World!")
}Variables
:= for immutable, mut for mutable.
vlang
x := 10 // immutable
mut y := 20 // mutable
y += 5Functions
Functions use fn; types come after parameter names.
vlang
fn add(a int, b int) int {
return a + b
}
fn main() {
println(add(3, 4))
}Run & Build
v run executes, v compiles to binary.
vlang
# v run main.v
# v -prod main.v # optimized build02
Types
Basic Types
V infers types automatically.
vlang
a := 1 // int
b := 3.14 // f64
s := "hello" // string
b2 := true // boolArrays
<< appends to array.
vlang
mut nums := [1, 2, 3]
nums << 4
println(nums.len)
println(nums[0])Maps
Maps are hash tables.
vlang
mut m := map[string]int{}
m["one"] = 1
m["two"] = 2
println(m["one"])Structs
Structs are the primary data structure.
vlang
struct Point {
x int
y int
}
p := Point{x: 10, y: 20}
println(p.x)03
Control Flow
If-Else
Standard if-else-if-else chain.
vlang
n := 5
if n > 3 {
println("big")
} else if n == 3 {
println("three")
} else {
println("small")
}Match
match for multi-way branching.
vlang
n := 2
match n {
1 { println("one") }
2 { println("two") }
else { println("other") }
}For Loop
.. is exclusive range.
vlang
for i in 0..5 {
println(i)
}
for num in [1, 2, 3] {
println(num)
}04
Advanced
Methods
Methods are functions with a receiver.
vlang
struct Rect {
w int
h int
}
fn (r Rect) area() int {
return r.w * r.h
}
r := Rect{w: 3, h: 4}
println(r.area())Error Handling
! marks functions that can return errors; or handles them.
vlang
fn divide(a int, b int) !int {
if b == 0 {
return error("division by zero")
}
return a / b
}
result := divide(10, 2) or { 0 }Was this helpful?