struct

类型定义

type Rect struct {   
    width, height float64
}

声明语义

var rect Rect

上面的声明语义会定义一个Rect对象,rect中的变量会被初始为对应的零值。

注意: struct对象没有零值,即不会出现 rect == nil的语句

初始化方法

rect := new(Rect)    # 指针
rect := &Rect{}    # 指针
rect := &Rect{1.0, 2.0}    # 指针
rect := &Rect{width: 1.0, height: 2.0}    # 指针
rect := Rect{width: 1.0, height: 2.0}    # 对象句柄

成员函数

成员函数的定义有两种:valueMethod 和 pointerMethod,如下:

  • pointerMethod

func (r *Rect) Area() float64 {
    return r.width * r.height
}
  • valueMethod

func (r Rect) Area() float64 {
    return r.width * r.height
}
  • valueMethod vs pointerMethod

可以把成员函数当成是一个普通的函数,value和pointer是函数的一个参数。那么,如果是valueMethod,在成员函数中,r是Rect对象的一个副本;如果是pointerMethod,r是Rect对象的指针。

我们可以通过以下的成员函数来比较它们的区别。

func (r *Rect) SetWidth(width float64) {
    r.width = width
}

func (r Rect) SetHeight(height float64) {
    r.height = height
}

rect1 := &Rect{}
rect2 := Rect{}
rect1.SetWidth(1)
rect1.SetHeight(1)
rect2.SetWidth(1)
rect2.SetHeight(1)

fmt.Println(rect1.width)
fmt.Println(rect1.height)
fmt.Println(rect2.width)
fmt.Println(rect2.height)

以上的输出为:

1
0
1
0

Last updated

Was this helpful?