patterngoCritical
Golang : Is conversion between different struct types possible?
Viewed 0 times
possiblestructbetweengolangtypesconversiondifferent
Problem
Let's say I have two similar types set this way :
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)
Thanks.
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)
Thanks.
Solution
For your specific example, you can easily convert it playground:
t1 := type1{{"A", 1}, {"B", 2}}
t2 := type2(t1)
fmt.Println(t2)Code Snippets
t1 := type1{{"A", 1}, {"B", 2}}
t2 := type2(t1)
fmt.Println(t2)Context
Stack Overflow Q#24613271, score: 112
Revisions (0)
No revisions yet.