• 结构体

    结构体

    1. struct Point {
    2. x int
    3. y int
    4. }
    5. p := Point{
    6. x: 10
    7. y: 20
    8. }
    9. println(p.x) // Struct fields are accessed using a dot

    上面的结构体都在栈上分配。如果需要在堆上分布,需要用取地址的&操作符:

    1. pointer := &Point{10, 10} // Alternative initialization syntax for structs with 3 fields or fewer
    2. println(pointer.x) // Pointers have the same syntax for accessing fields

    V语言不支持子类继承,但是可以嵌入匿名结构体成员:

    1. // TODO: this will be implemented later in June
    2. struct Button {
    3. Widget
    4. title string
    5. }
    6. button := new_button('Click me')
    7. button.set_pos(x, y)
    8. // Without embedding we'd have to do
    9. button.widget.set_pos(x,y)