forging2012
11/25/2017 - 3:51 AM

Get/set an field value of a struct

Get/set an field value of a struct

    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