You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
930 B
51 lines
930 B
3 years ago
|
package main
|
||
|
|
||
|
import "fmt"
|
||
|
|
||
|
type person struct {
|
||
|
city, name string
|
||
|
age int
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
//基本实例化
|
||
|
var p1 person //没有初始化的结构体,其成员变量都是对应其类型的零值。
|
||
|
p1.age = 10
|
||
|
p1.city = "anhui"
|
||
|
p1.name = "ld"
|
||
|
|
||
|
//匿名结构体
|
||
|
var user struct {
|
||
|
name string
|
||
|
age int
|
||
|
}
|
||
|
user.age = 10
|
||
|
user.name = "username"
|
||
|
fmt.Println(p1, user)
|
||
|
|
||
|
//创建指针类型结构体
|
||
|
var p2 = new(person)
|
||
|
fmt.Printf("p2: %T\n", p2)
|
||
|
fmt.Printf("p2: %#v\n", p2)
|
||
|
|
||
|
//取结构体地址的实例化
|
||
|
p3 := &person{}
|
||
|
fmt.Printf("p3: %T\n", p3)
|
||
|
fmt.Printf("p3: %#v\n", p3)
|
||
|
p3.age = 18 //本质在底层是执行的 (*p3).age = 18
|
||
|
p3.city = "beijing"
|
||
|
p3.name = "zhang san"
|
||
|
fmt.Printf("p3: %#v\n", p3)
|
||
|
|
||
|
p4 := newPerson("p4", "suzhou", 22)
|
||
|
fmt.Printf("p4: %#v\n", p4)
|
||
|
}
|
||
|
|
||
|
func newPerson(name, city string, age int) *person {
|
||
|
return &person{
|
||
|
city: city,
|
||
|
name: name,
|
||
|
age: age,
|
||
|
}
|
||
|
}
|