您好,登錄后才能下訂單哦!
// code_016_struct_anonymous_field2 project main.go
package main
import (
"fmt"
)
type Person struct {
name string
sex byte
age int
}
type Student struct {
Person
id int
addr string
name string //同名字段
}
type mystr string //自定義類型
type Student01 struct {
Person
int
mystr
}
type Person02 struct {
name string
sex byte
age int
}
type Student02 struct {
*Person02 //匿名字段,結(jié)構(gòu)體指針
id int
addr string
}
func main() {
//1)同名字段的使用
var s Student
s.name = "ck_god" //默認(rèn)給最外層的成員賦值
fmt.Printf("%+v\n", s)
s.Person.name = "god_girl" //顯示調(diào)用
fmt.Printf("%+v\n", s)
//2) 其他匿名字段
s1 := Student01{Person{"ck_god", 1, 18}, 1, "wz"}
fmt.Printf("%+v\n", s1)
//非結(jié)構(gòu)體類型的匿名成員的操作
fmt.Printf("%s,%c,%d,%d,%s\n",
s1.name, s1.sex, s1.age, s1.int, s1.mystr)
//3)結(jié)構(gòu)體指針類型
s3 := Student02{&Person02{"ck_god", 0, 18}, 1, "bj"}
fmt.Printf("%+v\n", s3)
fmt.Printf("%s,%c,%d\n", s3.name, s3.sex, s3.age)
var s2 Student02
s2.Person02 = new(Person02) //分配空間
s2.name = "ck"
s2.sex = 1
s2.age = 20
s2.id = 2
s2.addr = "sz"
fmt.Println(s2.name, s2.sex, s2.age, s2.id, s2.age)
}
輸出結(jié)果如下:
{Person:{name: sex:0 age:0} id:0 addr: name:ck_god}
{Person:{name:god_girl sex:0 age:0} id:0 addr: name:ck_god}
{Person:{name:ck_god sex:1 age:18} int:1 mystr:wz}
ck_god,,18,1,wz
{Person02:0xc000004480 id:1 addr:bj}
ck_god,,18
ck 1 20 2 20
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。