Structs

12.1 Defining and Creating Structs

struct Point {
	x int
	y int
}

p := Point{x: 10, y: 20}
p2 := Point{10, 20}          // positional (only for short structs, discouraged)
println(p.x)
println(p)                   // auto-generated string representation

12.2 Field Access Modifiers

Read outside module Write inside module Write outside module

struct User {
	id int                   // private, immutable (default)
mut:
	login_count int          // private, mutable
pub:
	name string              // public (read outside the module), immutable
pub mut:
	email string             // public, mutable outside the module
__global:
	debug bool               // public and mutable everywhere (rare)
}

12.3 Default Values and Required Fields

struct Config {
	host    string = 'localhost'
	port    int    = 8080
	debug   bool
	api_key string @[required]    // must be set at initialization
}
c := Config{api_key: 'secret'}

12.4 Mutability of Struct Instances

mut u := User{name: 'Ana'}
u.email = '[email protected]'        // needs both `mut u` and a mutable field

12.5 Struct Update Syntax

p1 := Point{x: 1, y: 2}
p3 := Point{...p1, y: 5}      // copy p1 with y changed

12.6 Embedded Structs (Composition)

struct Animal {
	name string
}
fn (a Animal) describe() string { return 'I am ${a.name}' }

struct Dog {
	Animal                    // embedding: fields and methods are promoted
	breed string
}

d := Dog{Animal: Animal{name: 'Rex'}, breed: 'Lab'}
println(d.name)               // promoted field
println(d.describe())         // promoted method
println(d.Animal.name)        // explicit access

12.7 Anonymous Structs and Short Struct Literals

book := struct {
	title  string
	author string
}{
	title:  'V Guide'
	author: 'Ana'
}
fn make() Point { return Point{1, 2} }

12.8 Heap Structs and References

p := &Point{x: 1, y: 2}       // allocated on the heap, p is a reference
println(p.x)                  // automatic dereference
@[heap]
struct BigData { buf [1024]u8 }   // always heap-allocated

12.9 Unions (Unsafe)

union IntOrFloat {
	i int
	f f32
}
v := IntOrFloat{f: 1.0}
unsafe { println(v.i) }