I’m trying to create a struct
and attaching fields
and methods/functions
to it, so I started with:
package main
import (
"reflect"
)
func main() {
s := reflect.Zero(reflect.TypeOf(reflect.Struct))
f := reflect.Zero(reflect.TypeOf(reflect.StructField{
Name: "id",
PkgPath: "",
Type: reflect.TypeOf(reflect.Int),
Tag: "",
Offset: 0,
Index: []int{},
Anonymous: false,
}))
m := reflect.Zero(reflect.TypeOf(reflect.Method{
Name: "add",
PkgPath: "",
Type: reflect.TypeOf(reflect.FuncOf(
[]reflect.Type{reflect.TypeOf(reflect.Int)},
[]reflect.Type{reflect.TypeOf(reflect.Int)},
false)),
Func: f,
Index: 0,
}))
swap := func(in []reflect.Value) []reflect.Value {
return []reflect.Value{in[1], in[0]}
}
t := reflect.ValueOf(&swap).Elem()
m.Set(reflect.MakeFunc(t.Type(), swap))
_ = m
_ = s
}
But at line m.Set(reflect.MakeFunc(t.Type(), swap))
I got the error:
panic: reflect: reflect.Value.Set using unaddressable value
goroutine 1 [running]:
reflect.flag.mustBeAssignableSlow(0x3?)
D:/Development/go/src/reflect/value.go:262 +0x85
reflect.flag.mustBeAssignable(...)
D:/Development/go/src/reflect/value.go:249
reflect.Value.Set({0xa7ff20?, 0xb53a60?, 0xa8c208?}, {0xa78500?, 0xc00008a210?, 0xa14313?})
D:/Development/go/src/reflect/value.go:2084 +0x6a
main.main()
D:/Deployment/Reflection/add.go:35 +0x3cf
exit status 2