The go language USES reflection to get and set the values of struct fields

  • 2020-05-26 09:20:22
  • OfStack

This example shows how the go language gets and sets the values of struct fields through reflection. Share with you for your reference. The specific implementation method is as follows:

type MyStruct struct {
        N int
}
n := MyStruct{ 1 } // get
immutable := reflect.ValueOf(n)
val := immutable.FieldByName("N").Int()
fmt.Printf("N=%d\n", val) // prints 1 // set
mutable := reflect.ValueOf(&n).Elem()
mutable.FieldByName("N").SetInt(7)
fmt.Printf("N=%d\n", n.N) // prints 7

I hope this article has been helpful to your programming of go language.


Related articles: