The program is:
package main
import (
"fmt"
"reflect"
)
type Request struct {
Method string
Resource string //path
Protocol string
}
type s struct {
ID int
Title string
Request Request
Price float64
Interface interface{}
Exists bool
Many []string
}
func main() {
s := s{}
iterateStruct(s)
}
func iterateStruct(s interface{}) {
e := reflect.ValueOf(s)
for i := 0; i < e.NumField(); i++ {
varName := e.Type().Field(i).Name
varKind := e.Field(i).Kind()
fmt.Println(e.Type().Field(i).Name)
if varKind == reflect.Struct {
//iterateStruct( <what should be here?>)
}
varType := e.Type().Field(i).Type
varValue := e.Field(i).Interface()
fmt.Printf("%v %v %v %v\n", varName, varKind, varType, varValue)
}
}
Using recursion I'd like to get the same information for Request, that is a structure part of a structure.
What would I need to pass as a parameter? I tried various ways but I have to reckon it's a lot of trial and error for me.
Try this:
if varKind == reflect.Struct {
iterateStruct(e.Field(i).Interface())
}
e.Field(i) returns the Value for the struct field. Interface{} will return the underlying value, so you can call iterateStruct using that.
Here's an example that handles fields with pointers to structs, interfaces containing struct value, etc.. As a bonus, this example indents nested structs.
func iterate(v reflect.Value, indent string) {
v = reflect.Indirect(v)
if v.Kind() != reflect.Struct {
return
}
indent += " "
for i := 0; i < v.NumField(); i++ {
varName := v.Type().Field(i).Name
varKind := v.Field(i).Kind()
varType := v.Type().Field(i).Type
varValue := v.Field(i).Interface()
fmt.Printf("%s%v %v %v %v\n", indent, varName, varKind, varType, varValue)
iterate(v.Field(i), indent)
}
}
Call it like this:
iterate(reflect.ValueOf(s), "")
https://go.dev/play/p/y1CzbKAUvD_w
Related
Below is a method which uses reflect package to modify fields of a struct ,this works for a specific struct type
func modify(obj Car) interface{} {
ty := reflect.TypeOf(obj)
for i := 0; i < ty.NumField(); i++ {
rval := reflect.Indirect(reflect.ValueOf(&obj))
field := rval.Field(i)
fieldType := field.Kind()
switch fieldType {
case reflect.String:
field.SetString("")
case reflect.Int:
field.SetInt(0)
case reflect.Ptr:
field.Set(reflect.ValueOf(nil))
}
}
return obj
}
modifying the signature to
func modify(obj interface{}) interface{} {
results in
panic: reflect: call of reflect.Value.Field on interface Value
at line
field := rval.Field(i)
https://go.dev/play/p/pGfKtIg5RUp
It works with the signature
func modify(obj Car) interface{} {
https://go.dev/play/p/31Oh6WLmlGP
Why is the compile time type modifying the behaviour ?
The goal here is to mask certain fields based on struct tags .It could wrap an endpoint and the input and output to the method being wrapped could be struct or pointer so in above case both calls should work
modify(car)
modify(&car)
This is how it works for both value and pointer types
func modify(obj interface{}) interface{} {
rv := reflect.ValueOf(obj)
trv := reflect.TypeOf(obj)
value := reflect.New(rv.Type())
if rv.Kind() == reflect.Pointer {
rv = reflect.ValueOf(obj).Elem()
trv = reflect.TypeOf(obj).Elem()
value = reflect.New(rv.Type())
}
for i := 0; i < rv.NumField(); i++ {
field := rv.Field(i)
fieldType := field.Kind()
v := value.Elem().Field(i)
tag, _ := trv.Field(i).Tag.Lookup("es")
if len(tag) != 0 {
switch fieldType {
case reflect.String:
v.SetString(tag)
case reflect.Int:
v.SetInt(0)
case reflect.Ptr:
v.Set(reflect.ValueOf(nil))
}
} else {
v.Set(field)
}
}
return value
}
https://go.dev/play/p/C1pqw_UbPcG
I'm trying to update all string fields in a struct and its subfields using reflection in golang for an arbitrary struct as follows:
package main
import (
"fmt"
"reflect"
"strings"
)
func main() {
type Inner struct {
In1 string
In2 []string
}
type Type struct {
Name string
Names []string
NewSt Inner
}
a := Type{
Name: " [ (Amir[ ",
Names: nil,
NewSt: Inner{
In1: " [in1",
In2: []string{" [in2( "},
},
}
trims(&a)
fmt.Printf("%#v\n", a)
}
func trim(str string) string {
return strings.TrimSpace(strings.Trim(str, "[](){}, "))
}
func trims(ps interface{}) {
v := reflect.ValueOf(ps).Elem() // Elem() dereferences pointer
for i := 0; i < v.NumField(); i++ {
fv := v.Field(i)
switch fv.Kind() {
case reflect.String:
fv.SetString(trim(fv.String()))
case reflect.Struct:
in := fv.Interface()
trims(&in)
}
}
}
But I get panic: reflect: call of reflect.Value.Elem on struct Value error.
How can I fix it or is there any better way that I can do such thing??
Thanks.
func trims(ps interface{}) {
v := reflect.ValueOf(ps)
if v.Kind() == reflect.Ptr {
v = v.Elem() // Elem() dereferences pointer
}
if v.Kind() != reflect.Struct {
panic("not struct")
}
for i := 0; i < v.NumField(); i++ {
fv := v.Field(i)
switch fv.Kind() {
case reflect.String:
fv.SetString(trim(fv.String()))
case reflect.Struct:
// use Addr() to get an addressable
// value of the field
in := fv.Addr().Interface()
// do not use &in, that evaluates
// to *interface{}, that's almost
// NEVER what you want
trims(in)
case reflect.Slice:
if fv.Type().Elem().Kind() == reflect.String {
for i := 0; i < fv.Len(); i++ {
fv.Index(i).SetString(trim(fv.Index(i).String()))
}
}
}
}
}
https://go.dev/play/p/JkJTJzTckNA
package main
import (
"fmt"
"reflect"
)
type PetDetails struct {
Name *string
}
type Student struct {
Fname string
Lname string
City string
Mobile *int
Pet *PetDetails
}
func main() {
i := 7777777777
petName := "Groot"
s := Student{"Chetan", "Tulsyan", "Bangalore", &i, &PetDetails{&petName}}
v := reflect.ValueOf(s)
typeOfS := v.Type()
for i := 0; i< v.NumField(); i++ {
fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
}
}
I am trying to convert these struct into map[string]string as I need the map for update query of mongoDB. After converting my struct to BSON, instead of querying { "pet.name": "Groot" } it becomes { "pet": { "name": "Groot" } } which deletes other fields inside the embedded document pet. I'm not sure how to override BSON marshals as I'm using mongodb driver, not mgo
I would like to get value of Mobile pointer and Name of the Pet, but all I get is the address
How can I get the value, e.g. 7777 and Groot ? Thanks
You can use Elem to dereference the pointer types.
x := 5
ptr := reflect.ValueOf(&x)
value := ptr.Elem()
ptr.Type().Name() // *int
ptr.Type().Kind() // reflect.Ptr
ptr.Interface() // [pointer to x]
ptr.Set(4) // panic
value.Type().Name() // int
value.Type().Kind() // reflect.Int
value.Interface() // 5
value.Set(4) // this works
For example, to retrieve the mobile number in your example you should change the loop in main to:
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
value := field.Interface()
// If a pointer type dereference with Elem
if field.Kind() == reflect.Ptr {
value = field.Elem().Interface()
}
fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, value)
}
I'm working on one of our system applications, specifically in the configuration file handling bits. We currently have 3 different places where a configuration file can be stored, and that can possibly be extended later. What I'm trying to do is simplify the way we need to add a new managed field.
The solution I have so far looks something like this:
package main
import (
"reflect"
"strconv"
"strings"
)
type Datastore interface{}
type MyInt struct {
intVal int
}
func NewMyInt(key string, dv int, db *Datastore) *MyInt {
// Do something here to construct MyInt
return &MyInt{intVal: dv}
}
type Config struct {
myInts map[string]*MyInt
// Tag is of form "<key in DB>:<default value>"
Value1 MyInt "value1_key:12345"
Value2 MyInt "value2_key:54321"
}
func NewConfig(db *Datastore) *Config {
c := &Config{
myInts: make(map[string]*MyInt),
}
cType := reflect.TypeOf(c)
for i := 0; i < cType.NumField(); i++ {
f := cType.Field(i)
if f.Name == "myInts" {
continue
}
tag := string(f.Tag)
fields := strings.Split(tag, ":")
switch f.Type.Name() {
case "myInt":
intVal, _ := strconv.Atoi(fields[1])
val := NewMyInt(fields[0], intVal, db)
c.myInts[fields[0]] = val
// How do I set the i'th field to this newly constructed value?
}
}
return c
}
So far I'm just missing this piece to do the assignment.
For this question, you can try
func NewConfig(db *Datastore) *Config {
c := &Config{
myInts: make(map[string]*MyInt),
}
cType := reflect.TypeOf(c).Elem() // have to use Elem() to get actual value
cValue := reflect.ValueOf(c).Elem()
for i := 0; i < cType.NumField(); i++ {
f := cType.Field(i)
if f.Name == "myInts" {
continue
}
tag := string(f.Tag)
fields := strings.Split(tag, ":")
switch f.Type.Name() {
case "MyInt":
intVal, _ := strconv.Atoi(fields[1])
val := NewMyInt(fields[0], intVal, db)
c.myInts[fields[0]] = val
// How do I set the i'th field to this newly constructed value?
cValue.Field(i).Set(reflect.ValueOf(val).Elem())
}
}
fmt.Println(c.Value1.intVal, c.Value2.intVal)
return c
}
I have two structs:
type A struct {
BankCode string `json:"bankCode"`
BankName string `json:"bankName"`
}
And:
type B struct {
A
extra string `json:" extra"`
}
And two slices:
listsA []A and listsB []B
I want to get bankCodes from listA and listB. bankcodes only contains bankcodes. It is a []string
It will be so easy as using two function.
func getBankCodes(data []A) []string {
res := make([]string, len(data))
for i := 0; i < len(data); i++ {
res[i] = data[i].BankCode
}
return res
}
func getBankCodes(data []B) []string {
res := make([]string, len(data))
for i := 0; i < len(data); i++ {
res[i] = data[i].BankCode
}
return res
}
How to use one common function ?
Well the clean solution would be to use an interface, since go doesn't support classic inheritance, so something like []parentclass can't work. Interfaces however can only describe functions not a common field, so you have to implement a Getter (essentially).
// GetBankCoder provides a function that gives the BankCode
type GetBankCoder interface {
getBankCode() string
}
// implement GetBankCoder for A (and indirectly for B)
func (a A) getBankCode() string {
return a.BankCode
}
and make your getBankCodes work on that interface type, notice the parameter of the function as well as the statement inside the loop:
func getBankCodes(data []GetBankCoder) []string { // <-- changed
res := make([]string, len(data))
for i := 0; i < len(data); i++ {
res[i] = data[i].getBankCode() // <-- changed
}
return res
}
There are other solutions where the function parameter is of interface{} type and then reflection is used to assure you can actually do .BankCode, but I don't like those, as they are not adding more clarity either.
... However, I couldn't get the golang playground to make this work correctly without putting it into a []GetBankCoder var first, before giving it to the function.
banks := make([]GetBankCoder, 0)
banks = append(banks, A{ BankCode: "ABC", BankName: "ABC Bank"})
getBankCodes(banks)
You may use one common function like so:
func BankCodes(data interface{}) []string {
if reflect.TypeOf(data).Kind() != reflect.Slice {
panic("err: data is not slice")
}
slice := reflect.Indirect(reflect.ValueOf(data))
res := make([]string, slice.Len())
for i := 0; i < slice.Len(); i++ {
a := slice.Index(i).Interface().(BankCoder)
res[i] = a.Bankcode()
}
return res
}
Code (try on The Go Playground):
package main
import (
"fmt"
"reflect"
)
func main() {
bs := []B{B{A{"BC1", "BN"}, "e"}, B{A{"BC2", "BN"}, "e"}}
strs := BankCodes(bs)
fmt.Println(strs)
as := []A{A{"AC1", "BN"}, A{"AC2", "BN"}}
strs2 := BankCodes(as)
fmt.Println(strs2)
}
func BankCodes(data interface{}) []string {
if reflect.TypeOf(data).Kind() != reflect.Slice {
panic("err: data is not slice")
}
slice := reflect.Indirect(reflect.ValueOf(data))
res := make([]string, slice.Len())
for i := 0; i < slice.Len(); i++ {
a := slice.Index(i).Interface().(BankCoder)
res[i] = a.Bankcode()
}
return res
}
type A struct {
BankCode string `json:"bankCode"`
BankName string `json:"bankName"`
}
type B struct {
A
extra string `json:" extra"`
}
type BankCoder interface {
Bankcode() string
}
func (a A) Bankcode() string {
return a.BankCode
}