golang初始化接口体的几种方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
type Rect struct {

    x, y float64

    width, height float64

}

初始化方法:

rect1 := new(Rect)

rect2 := &Rect{}

rect3 := &Rect{0, 0, 100, 200}

rect4 := &Rect{width:100, height:200}

注意这几个变量全部为指向Rect结构的指针(指针变量),因为使用了new()函数和&操作符.而如果使用方法

1
2
3


a := Rect{}

则表示这个是一个Rect{}类型.两者是不一样的

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20

func main() {

rect1 := &Rect{0, 0, 100, 200}

rect1.x = 10

 

a := Rect{}

a.x = 15

 

fmt.Printf("%v\n%T\n", a, a)

fmt.Printf("%v\n%T\n", rect1, rect1)

}