Go中的"继承"之struct的匿名字段2

栏目: Go · 发布时间: 7年前

内容简介:输出结果如下:
// 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 //匿名字段,结构体指针
    id        int
    addr      string
}

func main() {
    //1)同名字段的使用
    var s Student
    s.name = "ck_god" //默认给最外层的成员赋值
    fmt.Printf("%+v\n", s)

    s.Person.name = "god_girl" //显示调用
    fmt.Printf("%+v\n", s)

    //2) 其他匿名字段
    s1 := Student01{Person{"ck_god", 1, 18}, 1, "wz"}
    fmt.Printf("%+v\n", s1)

    //非结构体类型的匿名成员的操作
    fmt.Printf("%s,%c,%d,%d,%s\n",
        s1.name, s1.sex, s1.age, s1.int, s1.mystr)

    //3)结构体指针类型
    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)
}

输出结果如下:

{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

以上所述就是小编给大家介绍的《Go中的"继承"之struct的匿名字段2》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Host Your Web Site In The Cloud

Host Your Web Site In The Cloud

Jeff Barr / SitePoint / 2010-9-28 / USD 39.95

Host Your Web Site On The Cloud is the OFFICIAL step-by-step guide to this revolutionary approach to hosting and managing your websites and applications, authored by Amazon's very own Jeffrey Barr. "H......一起来看看 《Host Your Web Site In The Cloud》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具