Say I have a struct of UnnamedTypes:
type UnnamedTypes struct {
i []int
f []float64
}
And some named types in a struct:
type I []int
type F []float64
type NamedTypes struct {
i I
f F
}
What's the easiest way to assign NamedTypes struct to an UnnamedTypes struct?
func main() {
var u UnnamedTypes
var n NamedTypes
u.i = []int{1,2}
u.f = []float64{2,3}
n.i = []int{2,3}
n.f = []float64{4,5}
u = UnnamedTypes(n)
}
fails with cannot convert n (type NamedTypes) to type UnnamedTypes
Create a new struct value using the old ones.
u = UnnamedTypes{
i: n.i,
f: n.f,
}
A warning though, because these specific values are slices, the slices in the two different structs are the exact same slices. Modifying one will modify the other. The same will apply to any pointers as well (including maps and interfaces). If you want them to have their own copy, you must allocate a copy.