Upgrade to Pro — share decks privately, control downloads, hide ads and more …

pp and reflect

pp and reflect

Go Conference 2015 summer

Takashi Kokubun

June 21, 2015
Tweet

More Decks by Takashi Kokubun

Other Decks in Programming

Transcript

  1. k0kubun/pp • Prettily print any complex data structures • Simple

    APIs like “fmt” import "github.com/k0kubun/pp" for _, tweet := range tweets { pp.Println(tweet) }
  2. ؔ਺Λϥοϓͯ͠gitignore import p "github.com/k0kubun/pp" func pp(a ...interface{}) { p.Println(a...) }

    • ʮ,*ʯΛgitignoreͯ͠ΔͳΒʮ,.goʯͱ͔ • ࢖ͬͯͳͯ͘΋importফ͞ͳͯ͘ࡁΉ ղܾํ๏ɿ
  3. reflectͰͰ͖Δͷ͸࣍ͷ͏ͪͲΕʁ ૢ࡞ ճ౴ ؔ਺ఆٛ ˓ ؔ਺ݺͼग़͠ ˓ ϝιουఆٛ º ϝιουݺͼग़͠

    ˕ ೚ҙͷܕͷOFX ˓ ˕ɿstringͰ໊લΛࢦఆՄɹ˓ɿreflect.Value͔ΒՄೳɹ×ɿແཧ ϝλϓϩՄ
  4. reflectʹΑΔؔ਺ఆٛ • ೚ҙͷγάωνϟͷؔ਺Λ࡞ΕΔ var f func(int, int) int v :=

    reflect.MakeFunc( reflect.TypeOf(f), func(in []reflect.Value) []reflect.Value { return []reflect.Value{in[0]} }, ) reflect.ValueOf(&f).Elem().Set(v)
  5. reflectʹΑΔؔ਺ݺͼग़͠ • ೚ҙͷγάωνϟͷؔ਺Λݺͼग़ͤΔ f := func(a int, b int) int

    { return a + b } v := reflect.ValueOf(f) in := []reflect.Value{} for i := 0; i < v.Type().NumIn(); i++ { in = append(in, reflect.ValueOf(1)) } v.Call(in)
  6. reflectʹΑΔϝιουݺͼग़͠ • stringͰ໊લΛࢦఆͯ͠ϝιουΛݺͼग़ͤΔ type Hoge struct{} func (h Hoge) Foo()

    { print("foo") } func (h Hoge) Bar() { print("bar") } h := new(Hoge) for _, name := range []string{"Foo", "Bar"} { v := reflect.ValueOf(h) v.MethodByName(name).Call([]reflect.Value{}) }