Access to outstanding fields in golang / reflect?

Is there a way to use Reflect to access unfulfilled fields in go 1.8? This does not work anymore : https://stackoverflow.com/a/316618/

Note that it reflect.DeepEqualworks just fine (that is, it can access unexported fields), but I cannot make the heads or tails of this function. Here comes playarea, which shows this in action: https://play.golang.org/p/vyEvay6eVG . The src code is below

import (
"fmt"
"reflect"
)

type Foo struct {
  private string
}

func main() {
    x := Foo{"hello"}
    y := Foo{"goodbye"}
    z := Foo{"hello"}

    fmt.Println(reflect.DeepEqual(x,y)) //false
    fmt.Println(reflect.DeepEqual(x,z)) //true
}
+4
source share
2 answers

If the structure is addressable, you can use unsafe.Pointerto access the field (read or write), for example:

rs := reflect.ValueOf(&MyStruct).Elem()
rf := rs.Field(n)
// rf can't be read or set.
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
// Now rf can be read and set.

. .

unsafe.Pointer "" unsafe go vet .

, , :

rs = reflect.ValueOf(MyStruct)
rs2 := reflect.New(rs.Type()).Elem()
rs2.Set(rs)
rf = rs2.Field(0)
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
// Now rf can be read.  Setting will succeed but only affects the temporary copy.

. .

+6

reflect.DeepEqual() , reflect, valueInterface(), safe, Value.Interface(), safe=true. reflect.DeepEqual() () safe=false.

, Value.Interface() . , Value.String() string, Value.Float() float, Value.Int() ints .. ( ), ( "" , Value.Interface() , ).

, Value.Elem(), , / .

:

type Foo struct {
    s string
    i int
    j interface{}
}

func main() {
    x := Foo{"hello", 2, 3.0}
    v := reflect.ValueOf(x)

    s := v.FieldByName("s")
    fmt.Printf("%T %v\n", s.String(), s.String())

    i := v.FieldByName("i")
    fmt.Printf("%T %v\n", i.Int(), i.Int())

    j := v.FieldByName("j").Elem()
    fmt.Printf("%T %v\n", j.Float(), j.Float())
}

( Go Playground):

string hello
int64 2
float64 3
+1

Source: https://habr.com/ru/post/1671777/


All Articles