Skip to content

V Hoja de referencia

Lenguaje compilado simple, rápido y seguro para construir software mantenible.

01

Primeros pasos

Hola Mundo

println imprime con un salto de línea.

vlang
fn main() {
    println("Hello, World!")
}

Variables

:= para inmutable, mut para mutable.

vlang
x := 10        // immutable
mut y := 20    // mutable
y += 5

Funciones

Las funciones usan fn; los tipos van después de los nombres de los parámetros.

vlang
fn add(a int, b int) int {
    return a + b
}

fn main() {
    println(add(3, 4))
}

Ejecutar y compilar

v run ejecuta, v compila a binario.

vlang
# v run main.v
# v -prod main.v  # optimized build
02

Tipos

Tipos básicos

V infiere los tipos automáticamente.

vlang
a := 1          // int
b := 3.14       // f64
s := "hello"    // string
b2 := true      // bool

Arrays

<< añade elementos al array.

vlang
mut nums := [1, 2, 3]
nums << 4
println(nums.len)
println(nums[0])

Maps

Los maps son tablas hash.

vlang
mut m := map[string]int{}
m["one"] = 1
m["two"] = 2
println(m["one"])

Structs

Los structs son la estructura de datos principal.

vlang
struct Point {
    x int
    y int
}

p := Point{x: 10, y: 20}
println(p.x)
03

Flujo de control

If-Else

Cadena estándar if-else-if-else.

vlang
n := 5
if n > 3 {
    println("big")
} else if n == 3 {
    println("three")
} else {
    println("small")
}

Match

match para ramificación con múltiples caminos.

vlang
n := 2
match n {
    1 { println("one") }
    2 { println("two") }
    else { println("other") }
}

Bucle for

.. es un rango exclusivo.

vlang
for i in 0..5 {
    println(i)
}

for num in [1, 2, 3] {
    println(num)
}
04

Avanzado

Funciones con receptor

Son funciones que llevan un receptor, el tipo sobre el que operan.

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())

Manejo de errores

! marca las funciones que pueden devolver errores; or los maneja.

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?