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

Time:03-31

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.

CodePudding user response:

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.

  • Related