go面向对象-匿名字段

接口

go支持只提供类型而不写字段名的方式,也就是匿名字段,也称为嵌入字段

复制代码
package main

import "fmt"

//    go支持只提供类型而不写字段名的方式,也就是匿名字段,也称为嵌入字段

//人
type Person struct {
    name string
    sex  string
    age  int
}

type Student struct {
    Person
    id   int
    addr string
}

func main() {
    // 初始化
    s1 := Student{Person{"5lmh", "man", 20}, 1, "bj"}
    fmt.Println(s1)

    s2 := Student{Person: Person{"5lmh", "man", 20}}
    fmt.Println(s2)

    s3 := Student{Person: Person{name: "5lmh"}}
    fmt.Println(s3)
}

输出结果:

复制代码
    {{5lmh man 20} 1 bj}
    {{5lmh man 20} 0 }
    {{5lmh  0} 0 }

同名字段的情况

复制代码
package main

import "fmt"

//人
type Person struct {
    name string
    sex  string
    age  int
}

type Student struct {
    Person
    id   int
    addr string
    //同名字段
    name string
}

func main() {
    var s Student
    // 给自己字段赋值了
    s.name = "5lmh"
    fmt.Println(s)

    // 若给父类同名字段赋值,如下
    s.Person.name = "枯藤"
    fmt.Println(s)
}

输出结果:

复制代码
    {{  0} 0  5lmh}
    {{枯藤  0} 0  5lmh}

所有的内置类型和自定义类型都是可以作为匿名字段去使用

复制代码
package main

import "fmt"

//人
type Person struct {
    name string
    sex  string
    age  int
}

// 自定义类型
type mystr string

// 学生
type Student struct {
    Person
    int
    mystr
}

func main() {
    s1 := Student{Person{"5lmh", "man", 18}, 1, "bj"}
    fmt.Println(s1)
}

输出结果:

复制代码
    {{5lmh man 18} 1 bj}

指针类型匿名字段

复制代码
package main

import "fmt"

//人
type Person struct {
    name string
    sex  string
    age  int
}

// 学生
type Student struct {
    *Person
    id   int
    addr string
}

func main() {
    s1 := Student{&Person{"5lmh", "man", 18}, 1, "bj"}
    fmt.Println(s1)
    fmt.Println(s1.name)
    fmt.Println(s1.Person.name)
}

输出结果:

复制代码
    {0xc00005c360 1 bj}
    zs
    zs
相关推荐
Codebee19 小时前
30 分钟落地全栈交互:OneCode CLI+SVG 排课表实战
后端
合作小小程序员小小店19 小时前
游戏开发,桌面%小游戏,贪吃蛇%demo,基于vs2022,c语言,easyX,无数据库
c语言·开发语言
想搞艺术的程序员20 小时前
深入 NSQ 延迟消息实现原理:设计巧思与性能优化
性能优化·golang·nsq
x***J34820 小时前
Python多线程爬虫
开发语言·爬虫·python
TechTrek20 小时前
Spring Boot 4.0正式发布了
java·spring boot·后端·spring boot 4.0
m***D28620 小时前
Python网络爬虫实战案例
开发语言·爬虫·python
保持低旋律节奏20 小时前
C++——C++11特性
开发语言·c++·windows
飞梦工作室20 小时前
企业级 Spring Boot 邮件系统开发指南:从基础到高可用架构设计
java·spring boot·后端
haiyu柠檬20 小时前
在Spring Boot中实现Azure的SSO+VUE3前端配置
java·spring boot·后端
ID_1800790547320 小时前
基于 Python 的淘宝商品详情数据结构化解析:SKU、价格与库存字段提取
开发语言·数据结构·python