结构体
struct Point {
x int
y int
}
p := Point{
x: 10
y: 20
}
println(p.x) // Struct fields are accessed using a dot
上面的结构体都在栈上分配。如果需要在堆上分布,需要用取地址的&
操作符:
pointer := &Point{10, 10} // Alternative initialization syntax for structs with 3 fields or fewer
println(pointer.x) // Pointers have the same syntax for accessing fields
V语言不支持子类继承,但是可以嵌入匿名结构体成员:
// TODO: this will be implemented later in June
struct Button {
Widget
title string
}
button := new_button('Click me')
button.set_pos(x, y)
// Without embedding we'd have to do
button.widget.set_pos(x,y)