Examples

Working code to learn from. Each example is self-contained.

Hello World

hello_world.v
fn main() {
    println('Hello, world!')
}

Functions

functions.v
fn add(a int, b int) int {
    return a + b
}

fn main() {
    result := add(2, 3)
    println('2 + 3 = ${result}')
}

Structs & Methods

structs.v
struct Point {
    x f64
    y f64
}

fn (p Point) distance() f64 {
    return (p.x * p.x + p.y * p.y).sqrt()
}

fn main() {
    p := Point{x: 3.0, y: 4.0}
    println('Distance: ${p.distance()}')  // 5.0
}

Error Handling

errors.v
import os

fn read_config(path string) !string {
    content := os.read_file(path) or {
        return error('Failed to read ${path}: ${err}')
    }
    return content
}

fn main() {
    config := read_config('app.toml') or {
        eprintln('Error: ${err}')
        return
    }
    println(config)
}

HTTP Server

web.v
import net.http

fn main() {
    http.listen_and_serve('0.0.0.0:8080', fn (req http.Request) http.Response {
        return http.Response{
            body: 'Hello from Bear!'
            header: http.new_header_from_map({
                .content_type: 'text/plain'
            })
        }
    })
}

Concurrency

concurrency.v
import sync

fn worker(id int, ch chan string) {
    ch <- 'Worker ${id} done'
}

fn main() {
    ch := chan string{cap: 3}
    for i in 1 .. 3 {
        go worker(i, ch)
    }
    for _ in 0 .. 3 {
        println(<-ch)
    }
}

More examples in the repository:

Browse all examples on GitHub