Created
February 10, 2015 18:12
-
-
Save nickcarenza/f462457ae2ebb6f8face to your computer and use it in GitHub Desktop.
Using reflection to detect if type is slice and set property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import( | |
"fmt" | |
"reflect" | |
) | |
type X struct { | |
Prop int | |
} | |
func (x *X) method(){} | |
func main(){ | |
val1 := &X{} | |
doSomething(val1) | |
fmt.Println(val1) | |
fmt.Println("\n==========\n") | |
val2 := &[]X{X{},X{}} | |
doSomething(val2) | |
fmt.Println(val2) | |
} | |
func doSomething(v interface{}) { | |
//valType := reflect.TypeOf(v) | |
val := reflect.ValueOf(v) | |
fmt.Printf("%T\n",val) | |
fmt.Printf("%v\n",val) | |
if val.Kind() == reflect.Ptr { | |
elm := val.Elem() | |
fmt.Printf("%T\n",elm) | |
fmt.Printf("%v\n",elm) | |
if elm.Kind() == reflect.Slice { | |
for i:=0 ; i<elm.Len();i++ { | |
//for _, v := range elm.Pointer() { | |
//for _, v := range val { | |
//for _, v := range elm { | |
elm.Index(i).FieldByName("Prop").SetInt(2) | |
//val.Index(i).FieldByName("Prop").SetInt(2) | |
//v.FieldByName("Prop").SetInt(2) | |
//v.Prop = 2 | |
} | |
} else { | |
elm.FieldByName("Prop").SetInt(4) | |
//val.FieldByName("Prop").SetInt(4) | |
//elm.prop = 4 | |
//val.prop = 4 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment