英文:
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)
}
你可以尝试运行这段代码,它定义了两个结构体类型 SimpleInfo
和 ComplexInfo
,并在 main
函数中创建了一个 ComplexInfo
类型的变量 fa
,并给其成员变量 name
和 salary
赋值。最后,打印出 fa
的 name
和 salary
值。
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论