将一个 Golang 结构体加入到另一个结构体中。

huangapple go评论86阅读模式
英文:

Joining one Golang Struct into another

问题

我是一名初学者,从JavaScript转到Golang。有没有一种方法可以将一个Golang结构体加入到另一个结构体中?

示例:

type SimpleInfo struct {
    name string,
    age int,
}

type ComplexInfo struct {
    SimpleInfo,
    address string,
    salary int,
}

理想情况下,目的是使ComplexInfo看起来像这样:

{
    name string,
    age int,
    address string,
    salary int,
}
英文:

I'm a beginner to Golang coming from JavaScript land. Is there a way to join one Golang struct into another?

Example:

type SimpleInfo struct {
    name string,
    age int,
}

type ComplexInfo struct {
    SimpleInfo,
    address string,
    salary int,
}

Ideally, the intention is to make ComplexInfo look like this:

{
    name string,
    age int,
    address string,
    salary int,
}

答案1

得分: 2

你正在走在正确的道路上,不要使用逗号。

import (
	"fmt"
)


type SimpleInfo struct {
    name string
    age int
}

type ComplexInfo struct {
    SimpleInfo
    address string
    salary int
}

func main() {
    fa := ComplexInfo{}    
    fa.name = "frank"
    fa.salary = 1000000
    fmt.Println(fa.name, fa.salary)
}

你可以尝试运行这段代码,它定义了两个结构体类型 SimpleInfoComplexInfo,并在 main 函数中创建了一个 ComplexInfo 类型的变量 fa,并给其成员变量 namesalary 赋值。最后,打印出 fanamesalary 值。

英文:

You are on the right road, don't use commas

import (
	"fmt"
)


type SimpleInfo struct {
    name string
    age int
}

type ComplexInfo struct {
    SimpleInfo
    address string
    salary int
    }

func main() {
	fa:=ComplexInfo{}	
        fa.name="frank"
        fa.salary=1000000
	fmt.Println(fa.name, fa.salary)
}

huangapple
  • 本文由 发表于 2021年10月20日 01:41:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/69635448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定