Representative examples of V
syntax include:
Hello world The
"Hello, World!" program in V: fn main() { println("Hello, World!") }
Variables Variables are immutable by default and are defined using and a value. Use the
reserved word (keyword) to make them mutable. Mutable variables can be assigned to using : x := 1 mut y := 2 y = 3 Redeclaring a variable, whether in an
inner scope or in the same scope, is not allowed: x := 1 { x := 3 // error: redefinition of x } x := 2 // error: redefinition of x
Structs Struct example: struct Foo { number int name string score f32 } // Struct fields can be initialized by name var1 := Foo { number: 21 name: "baz" score: 2.5 } // or by position var2 := Foo{50, "taz", 3.14}
Heap structs By default, structs are allocated via
stack-based memory allocation (on the stack). When structs are referenced by using the prefix or have the attribute, they are allocated via
heap-based memory allocation (on the heap) instead: struct Foo { number int } @[heap] struct Baz { number f32 } // Structs that are referenced are heap allocated var1 := &Foo{2} // Baz is always heap allocated because of its [heap] attribute var2 := Baz{4.5}
Methods Methods in V are functions defined with a receiver
argument. The receiver appears in its own argument list between the keyword and the method name. Methods must be in the same
module as the receiver type. The enrolled_status method (below) has a receiver of type named . The convention is not to use receiver names like self or this, but preferably a short name. For example: struct Client { enrolled bool } fn (x Client) enrolled_status() bool { return x.enrolled } println(Client{enrolled: true}.enrolled_status()) // true println(Client{enrolled: false}.enrolled_status()) // false
Error handling Result types may represent an error returned from a function. Result types are declared by prepending : Optional types may represent . Option types prepend to the type name: . fn something(t string) !string { if t == "foo" { return "foo" } return error("invalid") } x := something("foo") or { "default" } // x will be "foo" y := something("baz") or { "default" } // y will be "default" z := something("baz") or { panic("{err}") } // z will exit with an error println(x) println(y) ==See also==