Golang : Is conversion between different struct types possible?


Let’s say I have two similar types set this way :

type type1 []struct {
    Field1 string
    Field2 int
type type2 []struct {
    Field1 string
    Field2 int

Is there a direct way to write values from a type1 to a type2, knowing that they have the same fields ?
(other than writing a loop that will copy all the fields from the source to the target)



For your specific example, you can easily convert it playground:

t1 := type1{{"A", 1}, {"B", 2}}
t2 := type2(t1)

Answered By – OneOfOne

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.