Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created August 2, 2020 06:19
Show Gist options
  • Save mmitou/77062510c1c3b69c1d3458b8973cb878 to your computer and use it in GitHub Desktop.
Save mmitou/77062510c1c3b69c1d3458b8973cb878 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
type ID struct {
CountryName string `hoge:"hello,foo" json:"cname"`
Index int `hoge:"world" json:"hogege"`
}
type Foo struct {
ID
string
}
func (*Foo) m() {
}
type Callable interface {
m()
}
func initFoo(obj interface{}) error {
v := reflect.ValueOf(obj)
if v.Type().Kind() != reflect.Ptr {
return fmt.Errorf("not ptr")
}
if v.IsNil() {
return fmt.Errorf("nil")
}
s := v.Elem()
if s.Type().Kind() != reflect.Struct {
return fmt.Errorf("not struct")
}
fld := s.FieldByName("CountryName")
if fld.Type().Kind() == reflect.Invalid {
return fmt.Errorf("not exist")
}
// fld.Set(reflect.ValueOf("america"))
fld.SetString("ame")
return nil
}
type Hoge struct {
ID string
Index int
}
type Hage struct {
ID string
Index int
}
func service(name string) interface{} {
m := map[string]reflect.Type{"Hoge": reflect.TypeOf(Hoge{}), "Hage": reflect.TypeOf(Hage{})}
v := reflect.New(m[name])
fmt.Println(v)
fmt.Println(v.Type())
e := v.Elem()
fld := e.FieldByName("ID")
fld.SetString("1234")
return e.Interface()
}
func main() {
i := service("Hoge")
fmt.Println(i)
}
func main5() {
id := ID{"japan", 100}
initFoo(&id)
fmt.Println(id)
}
func main4() {
var c Callable = &Foo{}
t := reflect.TypeOf(c)
fmt.Println(t)
fmt.Println(t.Kind())
c.m()
}
func main3() {
foo := &Foo{}
v := reflect.ValueOf(foo)
t := v.Type()
pstyp := reflect.TypeOf((*fmt.Stringer)(nil))
fmt.Println(pstyp)
styp := pstyp.Elem()
fmt.Println(styp)
fmt.Println("Does Type t implements Stringer?", t.Implements(styp))
}
func main2() {
foo := &Foo{}
v := reflect.ValueOf(foo)
if v.Kind() != reflect.Ptr {
panic("not pointer")
}
if v.IsNil() {
panic("nil")
}
fmt.Println(v.Type())
e := v.Elem()
fmt.Println(e.Type())
}
func main1() {
// f := Foo{ID{CountryName: "Japan", Index: 1}, "hello"}
f := ID{CountryName: "Japan", Index: 1}
fmt.Println(f)
v := reflect.ValueOf(f)
k := v.Kind()
fmt.Println(k)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("%+v\n", field)
}
}
func main0() {
m := map[string]int{"hello": 100, "world": 200}
v := reflect.ValueOf(m)
ks := v.MapKeys()
fmt.Println(ks)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment