How to copy content of an struct into a newly instantiated struct that extended the original struct?

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

How to copy content of an struct into a newly instantiated struct that extended the original struct?

问题

假设我有一个扩展另一个结构体的结构体。所以...

type Foo struct { A, B int64 }

type FooBar struct { 
                     Foo
                     Bar string
                    }

我有一个包含某些值的 foo 结构体。我想创建一个 foobar 结构体,其中包含 foo 的内容,并将 bar 设置为某个值。我的问题是,将 foo 结构体的内容复制到新实例化的 foobar 结构体中的最简洁方法是什么?

myFoo := generateFoo()

myFooBar := ???

我假设有一种语法糖可以实现这一点,但是我在谷歌上找不到。对于我的实际用例,浅拷贝就足够了,但是如果可以进行深拷贝,那就更好了。

英文:

Lets say I have a struct that extends another struct. so...

type Foo struct { A, B int64 }

type FooBar struct { 
                     Foo
                     Bar String
                    }

I have a foo struct with some value already contained within. I want to make a foobar struct with the content of foo plus bar being set to some value. My question is what is the cleanest way to copy the contents of my foo struct into my newly instantiated foobar struct?

myFoo := generateFoo()

myFooBar := ???

I assume there is some sort of syntactical sugar for this, but If so I swear I can't find it googling. For my actual use-case a shallow copy would suffice, but it would be good to know if a deep copy can be done as well.

答案1

得分: 4

不需要糖。值总是被复制。

myFoo := generateFoo()
myFooBar := FooBar { myFoo, myBar }

请注意,Go语言中没有"extends"关键字,也没有类型层级结构。

英文:

No sugar needed. Values are always copied.

myFoo := generateFoo()
myFooBar := FooBar { myFoo, myBar }

Note that there is no "extends" in Go, and no type hierarchy.

huangapple
  • 本文由 发表于 2022年3月30日 22:41:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/71679355.html
匿名

发表评论

匿名网友

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

确定