Skip to content

Instantly share code, notes, and snippets.

@tenntenn
Last active January 18, 2018 06:54
Show Gist options
  • Save tenntenn/6619291 to your computer and use it in GitHub Desktop.
Save tenntenn/6619291 to your computer and use it in GitHub Desktop.
Go言語におけるinterface{}とリフレクションを使ったパターン ref: https://qiita.com/tenntenn/items/a06b6b178959e3a63196
package main
import (
"fmt"
"reflect"
)
func call(f interface{}) {
fv := reflect.ValueOf(f)
if fv.Kind() != reflect.Func {
panic("f must be func.")
}
fv.Call([]reflect.Value{})
}
func main() {
f := func() {
fmt.Println("hello!")
}
call(f)
}
package main
import (
"fmt"
"reflect"
)
func set(p, v interface{}) error {
pv := reflect.ValueOf(p)
if pv.Kind() != reflect.Ptr {
return fmt.Errorf("p must be pointer.")
}
vv := reflect.ValueOf(v)
if pv.Elem().Kind() != vv.Kind() {
return fmt.Errorf("p type and v type do not mutch")
}
pv.Elem().Set(vv)
return nil
}
func main() {
var hoge int
fmt.Println(hoge)
set(&hoge, 100)
fmt.Println(hoge)
fmt.Println(set(&hoge, 10.4))
}
package main
import (
"fmt"
"reflect"
)
func call(f interface{}) {
fv := reflect.ValueOf(f)
if fv.Kind() != reflect.Func {
panic("f must be func.")
}
fv.Call([]reflect.Value{})
}
func main() {
f := func() {
fmt.Println("hello!")
}
call(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment