I don't seem to understand how reflect.Value.FieldByName() works:
package main
import (
"fmt"
"reflect"
)
func main() {
type X struct {
a int "one"
b int "two"
}
x := X{5, 7}
v := reflect.ValueOf(interface{}(x))
fmt.Println(x, v, v.Kind(), v.IsValid(), v.FieldByName("two"))
}
Produces:
{5 7} <main.X Value> struct true <invalid Value>
According to the docs this means that v.FieldByName("two") has returned
the zero value; but I was expecting a reflect.Value that held int 7.
What am I doing wrong?
Thanks!
$ hg identify
95d2ce135523+ (release-branch.r57) release/release.r57.1
--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Advanced Qt Programming" - ISBN 0321635906
http://www.qtrac.eu/aqpbook.html
Hi,I don't seem to understand how reflect.Value.FieldByName() works:
package main
import (
"fmt"
"reflect"
)
func main() {
type X struct {
a int "one"
b int "two"
}
x := X{5, 7}
v := reflect.ValueOf(interface{}(x))
fmt.Println(x, v, v.Kind(), v.IsValid(), v.FieldByName("two"))
}Produces:
{5 7} <main.X Value> struct true <invalid Value>
According to the docs this means that v.FieldByName("two") has returned
the zero value; but I was expecting a reflect.Value that held int 7.What am I doing wrong?
That works perfectly!
But I'm still curious as to how I can access struct field annotations?
Thanks:-)
--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Go" - ISBN 0321774639
http://www.qtrac.eu/gobook.html
v.FieldByName("b") should return (reflect.StructField, bool), according
to the docs, but actually returns a reflect.Value (which has the
expected int).
So I think that maybe the docs are wrong?
--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Rapid GUI Programming with Python and Qt" - ISBN 0132354187
http://www.qtrac.eu/pyqtbook.html
v.FieldByName("b") should return (reflect.StructField, bool), according
to the docs, but actually returns a reflect.Value (which has the
expected int).
So I think that maybe the docs are wrong?
Yes, sorry, my mistake (I mixed up TypeOf() and ValueOf()):
package main
import (
"fmt"
"reflect"
)
func main() {
type X struct {
a int "one"
b int "two"
}
x := X{5, 7}
v := reflect.ValueOf(x)
s := reflect.TypeOf(x)
f, ok := s.FieldByName("a")
fmt.Println(x, v, v.Kind(), v.IsValid(), v.FieldByName("b"))
fmt.Println(s, f, f.Tag, ok)
}
Correctly outputs:
{5 7} <main.X Value> struct true <int Value>
main.X {main a int one 0 [0] false} one true
--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy