1,按结构体顺序赋值
package main
import(
"fmt"
)
type boby struct {
id int
name string
age int
}
var b = boby{0,"annie",20}
func main() {
fmt.Printf("The boby's name is %s", b.name)
}
2,按结构体字段名赋值
package main
import(
"fmt"
)
type boby struct {
id int
name string
age int
}
var b boby
func main() {
b.id=0
b.name="minmin"
b.age=10
fmt.Printf("The boby's name is %s", b.name)
}
结构体嵌套
package main
import (
"fmt"
)
type Address struct {
Province string
City string
}
type User struct {
Username string
Sex string
address Address
}
type User1 struct {
Username string
Sex string
address *Address
}
func main(){
user := &User{
Username : "user01",
Sex :"男",
address : Address{
Province:"北京",
City:"北京",
},
}
fmt.Printf("user=%#v\n",user)
user1 :=&User1{
Username : "user01",
Sex :"男",
address : &Address{ // 如果Address是指针类型的,要加取值符&, &Address
Province:"北京",
City:"北京",
},
}
fmt.Printf("user1=%#v\n",user1)
}
输出:
user=&main.User{Username:"user01", Sex:"男", address:main.Address{Province:"北京", City:"北京"}}
user1=&main.User1{Username:"user01", Sex:"男", address:(*main.Address)(0xc000092440)}