Data structures

For changeability, structures work in exactly the same way as the basic types; we need to obtain the reflection of the pointer, then access its element in order to be able to change the value, because using the structure directly would produce a copy of it and it would panic when changing values.

We can replace the value of the entire structure using the Set method, after obtaining the new value's reflection:

func main() {
type X struct {
A, B int
c string
}
var a = X{10, 100, "apple"}
fmt.Println(a)
e := reflect.ValueOf(&a).Elem()
fmt.Println(e.String(), e.CanSet())
e.Set(reflect.ValueOf(X{1, 2, "banana"}))
fmt.Println(a)
}

A full example is available here: https://play.golang.org/p/mjb3gJw5CeA.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.194.57