Last active
January 18, 2018 06:54
-
-
Save tenntenn/6619291 to your computer and use it in GitHub Desktop.
Go言語におけるinterface{}とリフレクションを使ったパターン ref: https://qiita.com/tenntenn/items/a06b6b178959e3a63196
This file contains hidden or 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" | |
) | |
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) | |
} |
This file contains hidden or 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" | |
) | |
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)) | |
} | |
This file contains hidden or 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" | |
) | |
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