Anonymous field of "inherited" struct in Go

Source: Internet
Author: User

// code_016_anonymous_field project main.gopackage mainimport ( "fmt")type Person struct { name string sex byte age int}type Student struct { // 一般情况下,定义结构体的时候,字段名和类型一一对应,如下:Person为类型,并无字段名。 Person //匿名字段,name默认Student就包含了Person的所有字段。 id int addr string}func main() { //顺序初始化 s1 := Student{Person{"ck_god", 1, 18}, 1, "sz"} fmt.Printf("s1=%+v\n", s1) //部分成员初始化1 s2 := Student{Person: Person{"xiaobai", 0, 20}, id: 2, addr: "sz"} //部分成员初始化2 s3 := Student{Person: Person{name: "kavai"}, id: 3} fmt.Println(s2, s3) //访问成员变量 var s4 Student s4.name = "ck_god" s4.sex = 1 s4.age = 18 s4.id = 1 s4.addr = "sz" fmt.Println(s4) //访问成员变量2 var s5 Student s5.Person = Person{"god_girl", 1, 23} s5.id = 2 s5.addr = "wz" fmt.Println(s5)}
s1={Person:{name:ck_god sex:1 age:18} id:1 addr:sz}{{xiaobai 0 20} 2 sz} {{kavai 0 0} 3 }{{ck_god 1 18} 1 sz}{{god_girl 1 23} 2 wz}

Anonymous field of "inherited" struct in Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.