0

I'm aware that since Go 1.8 it's possible to assign one struct to another struct type like this:

func example() { type T1 struct { X intjson:"foo" } type T2 struct { X intjson:"bar" } var v1 T1 var v2 T2 v1 = T1(v2) // now legal }

However, if the struct internally has one of its fields as another struct, it doesn't work.

Playground: https://play.golang.org/p/tSHdjBhhAJ

What is the best way to assign 2 structs in this case apart from manually assigning each field?

This is not a duplicate of Assign struct with another struct since here, you're assigning a struct to another struct of the same type. However what I want is assigning two different structs having the same field names.

3
  • 1
    The new Go 1.8 feature only works if the structures have the same field names and types. Despite the fact that your Test2 and Test4 structures are identical by fields, they are two separate types, and thus the compiler disallows their assignment. One might argue that structures should be deep-compared instead of a simple type comparison, but that's not how it's implemented currently. You have three options: use the same struct type for the struct field in each, use an anonymous struct in each (play.golang.org/p/Hw7HANwqbZ), or make a helper function to convert the two manually. Commented Jun 20, 2017 at 15:05
  • Reopened. @Kaedys wanna post that as an answer? Commented Jun 20, 2017 at 15:55
  • Reposted as answer. Commented Jun 20, 2017 at 17:06

1 Answer 1

3

The new Go 1.8 feature only works if the structures have the same field names and types. Despite the fact that your Test2 and Test4 structures are identical by fields, they are two separate types, and thus the compiler disallows their assignment. One might argue that structures should be deep-compared instead of a simple type comparison, but that's not how it's implemented currently. You have three options: use the same struct type for the struct field in each, use an anonymous struct in each (https://play.golang.org/p/Hw7HANwqbZ), or make a helper function to convert the two manually.

There's currently a proposal out to allow deeply-equivalent structures to be converted without a field-by-field helper method, but it is currently slated for Go 2.x: https://github.com/golang/go/issues/20621

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.