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

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

Joining one Golang Struct into another

问题

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

示例:

  1. type SimpleInfo struct {
  2. name string,
  3. age int,
  4. }
  5. type ComplexInfo struct {
  6. SimpleInfo,
  7. address string,
  8. salary int,
  9. }

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

  1. {
  2. name string,
  3. age int,
  4. address string,
  5. salary int,
  6. }
英文:

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

Example:

  1. type SimpleInfo struct {
  2. name string,
  3. age int,
  4. }
  5. type ComplexInfo struct {
  6. SimpleInfo,
  7. address string,
  8. salary int,
  9. }

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

  1. {
  2. name string,
  3. age int,
  4. address string,
  5. salary int,
  6. }

答案1

得分: 2

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

  1. import (
  2. "fmt"
  3. )
  4. type SimpleInfo struct {
  5. name string
  6. age int
  7. }
  8. type ComplexInfo struct {
  9. SimpleInfo
  10. address string
  11. salary int
  12. }
  13. func main() {
  14. fa := ComplexInfo{}
  15. fa.name = "frank"
  16. fa.salary = 1000000
  17. fmt.Println(fa.name, fa.salary)
  18. }

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

英文:

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

  1. import (
  2. "fmt"
  3. )
  4. type SimpleInfo struct {
  5. name string
  6. age int
  7. }
  8. type ComplexInfo struct {
  9. SimpleInfo
  10. address string
  11. salary int
  12. }
  13. func main() {
  14. fa:=ComplexInfo{}
  15. fa.name="frank"
  16. fa.salary=1000000
  17. fmt.Println(fa.name, fa.salary)
  18. }

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:

确定