Structs in V

Posted by yhuang
Last Edited by dhonx
Public (Editable by Users)
V
None
Edit
module main

/* STRUCT EXAMPLE 1 */
struct Point {
	x int
	y int
}

fn example1() {
	p := Point{
		x: 10
		y: 20
	}
	println(p.x) // Struct fields are accessed using a dot
}

/* STRUCT EXAMPLE 2 */
fn example2() {
	// Structs are allocated on the stack. To allocate a struct on the heap and get a reference to it, use the & prefix:
	// Alternative initialization syntax for structs with 3 fields or fewer
	p := &Point{330, 10}
	// References have the same syntax for accessing fields 
	println(p.x)
	// The type of p is &Point. It's a reference to Point. References are similar to Go pointers and C++ references.

}



/* STRUCT EXAMPLE 4 */

// Structs can have default values:
struct Foo {
  a int
  b int = 10
}

fn example4() {
	foo := Foo{}
	assert foo.a == 0
	assert foo.b == 10
    println(foo)
}

fn main() {
    example1()
    example2()
    example4()
}