package main
import (
"fmt"
)
//定义结构体
type shape struct {
width int
height int
}
//初始化结构体四种方法
func main(){
//方法1
shape1 := new(shape)
fmt.Printf(" %d\n",shape1.width) //输出0
//方法2
shape2 := &shape{}
fmt.Printf(" %d\n",shape2.width)
//方法3
shape3 := &shape{10, 20} //这种需要赋值参数与结构体的变量个数一致, shape3 := &shape{10} 这样赋值是错误的
fmt.Printf(" %d\n",shape3.width)
//方法4
shape4 := &shape{width:10, height:20}
fmt.Printf(" %d\n",shape4.height)
//方法5
var shape5 shape
fmt.Printf(" %d\n",shape5.height)
//方法6
var shape6=shape{width:1} //只对部分成员变量进行初始化
fmt.Printf(" %d\n",shape6.width)
}
输出结果:
> Environment:
> GOPATH=C:\Users\qingshuic\go
> Directory: C:\Program Files\Go\my-jin
> Command: "C:\Program Files\Go\bin\go.exe" run -v "C:\Program Files\Go\my-jin\初始化结构体.go"
> Output:
command-line-arguments
0
0
10
20
0
1
> Elapsed: 1.594s
> Result: Success