go 语言 struct 另类构造函数 继承

1. go 中struct 没有构造函数,但是可以使用另一种方式来构造。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type School struct {
    Name string
    Addr string
}
 
func NewSchool(name, addr string) *School {
    return &School {
        Name:name,
        Addr:addr,
    }
}
func testNewSchool(){
    s1:= NewSchool("清华大学","北京海淀") //生成实例
    fmt.Println(*s1)
}
func main() {
    testNewSchool()
}
//运行结果
{清华大学 北京海淀}

  2.匿名函数实现继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type People struct{
    Name string
    Age int
}
type Student struct {
    Score int
    People
}
func test1(){
    var s Student
    s.Name = "abc"
    s.Age = 100
    s.Score = 200
    fmt.Printf("%#v\n",s)
}
//运行结果
main.Student{Score:200, People:main.People{Name:"abc", Age:100}}

  上面可以看出s相当于继承了People的 Name 和Age属性

如果Student有Name和Age属性呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type People struct{
    Name string
    Age int
}
type Student struct {
    Score int
    Name string
    Age int
    People
}
func test1(){
    var s Student
    s.Name = "abc"
    s.Age = 100
    s.Score = 200
    fmt.Printf("%#v\n",s)
}<br>//运行结果
main.Student{Score:200, Name:"abc", Age:100, People:main.People{Name:"", Age:0}}

  从上面输出结果可以看出,自己的属性覆盖了继承的属性,如果给匿名字段属性赋值呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
type People struct{
    Name string
    Age int
}
type Student struct {
    Score int
    Name string
    Age int
    People
}
func test1(){
    var s Student
    s.Name = "abc"
    s.Age = 100
    s.Score = 200
    s.People.Name = "def"
    s.People.Age = 20
    fmt.Printf("%#v\n",s)
}
//运行结果:
main.Student{Score:200, Name:"abc", Age:100, People:main.People{Name:"def", Age:20}}

  

 

posted @   whj999  阅读(342)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示