不同匿名结构体内具有相同名称的字段
创始人
2025-01-09 12:30:25
0

在Go语言中,可以使用嵌套结构体的方式来解决不同匿名结构体内具有相同名称的字段的问题。具体的代码示例如下:

package main

import "fmt"

type Person struct {
    name string
    age  int
}

type Student struct {
    Person
    score int
}

type Teacher struct {
    Person
    salary int
}

func main() {
    student := Student{
        Person: Person{
            name: "Tom",
            age:  18,
        },
        score: 90,
    }

    teacher := Teacher{
        Person: Person{
            name: "Alice",
            age:  30,
        },
        salary: 5000,
    }

    fmt.Println(student.name)   // Tom
    fmt.Println(student.age)    // 18
    fmt.Println(student.score)  // 90

    fmt.Println(teacher.name)   // Alice
    fmt.Println(teacher.age)    // 30
    fmt.Println(teacher.salary) // 5000
}

在上述代码中,Person结构体拥有name和age两个字段,Student结构体和Teacher结构体都嵌套了Person结构体,并且分别定义了自己独有的字段。通过这种方式,就可以在不同的匿名结构体内使用相同名称的字段,而不会产生冲突。

相关内容

热门资讯

hhpoker德州有挂吗!we... hhpoker德州有挂吗!wejoker私人辅助软件(透视)技巧-好像总结真的有挂1)wejoker...
红龙poker辅助平台!菠萝德... 红龙poker辅助平台!菠萝德州透视脚本(透视)教程-果然解迷存在有挂1)菠萝德州透视脚本有没有挂:...
拱趴大菠萝十三水透视!德普软件... 拱趴大菠萝十三水透视!德普软件(透视)教程-其实开挂存在有挂1、拱趴大菠萝十三水透视脚本辅助下载、拱...
德州透视是真的吗!hhpoke... 德州透视是真的吗!hhpoker破解工具(透视)app-一直开挂是有挂1、德州透视是真的吗辅助器安装...
wepoker买钻石有用吗!a... wepoker买钻石有用吗!aapoker透视方法(透视)方法-一直了解真的有挂1.wepoker买...
werplan怎么透视!htx... werplan怎么透视!htx矩阵wepoker辅助(透视)器-原来曝光真的有挂1、htx矩阵wep...
hhpoker真的假的!hhp... hhpoker真的假的!hhpoker买挂(透视)挂-一直了解真的是有挂1、hhpoker真的假的公...
pokemomo辅助工具!we... pokemomo辅助工具!we poker辅助器v3.3(透视)插件-果然解密是有挂1、用户打开应用...
红龙poker有辅助吗!wep... 红龙poker有辅助吗!wepoker辅助工具(透视)软件-都是必备存在有挂1、游戏颠覆性的策略玩法...
wepoker黑侠破解!wep... wepoker黑侠破解!wepoker透视苹果系统(透视)软件-果然关于存在有挂1、操作简单,无需w...