Last active
July 5, 2019 09:41
-
-
Save xin053/6e79c27cb537619722f99c319b504cb3 to your computer and use it in GitHub Desktop.
[go interface{}] go interface{} #go #interface
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
| // 故意在接口中定义方法, 以防止其他类型无意中实现了该接口 | |
| type runtime.Error interface { | |
| error | |
| RuntimeError() | |
| } | |
| // or | |
| type testing.TB interface { | |
| Error(args ...interface{}) | |
| Errorf(format string, args ...interface{}) | |
| // 私有方法, 这样只有该包下的类型才可以实现该接口 | |
| private() | |
| } |
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
| // range over interface{} which stores a slice | |
| package main | |
| import "fmt" | |
| import "reflect" | |
| func main() { | |
| data := []string{"one","two","three"} | |
| test(data) | |
| moredata := []int{1,2,3} | |
| test(moredata) | |
| } | |
| func test(t interface{}) { | |
| switch reflect.TypeOf(t).Kind() { | |
| case reflect.Slice: | |
| s := reflect.ValueOf(t) | |
| for i := 0; i < s.Len(); i++ { | |
| fmt.Println(s.Index(i)) | |
| } | |
| } | |
| } | |
| // Or, You don't need to use reflection if you know which types to expect. | |
| package main | |
| import "fmt" | |
| func main() { | |
| loop([]string{"one", "two", "three"}) | |
| loop([]int{1, 2, 3}) | |
| } | |
| func loop(t interface{}) { | |
| switch t := t.(type) { | |
| case []string: | |
| for _, value := range t { | |
| fmt.Println(value) | |
| } | |
| case []int: | |
| for _, value := range t { | |
| fmt.Println(value) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment