funcmain() { var i io.Reader // 此处i是为未初始化的接口变量,所以v为nil switch v := i.(type) { casenil: // <nil> fmt.Printf("%T\n", v) default: fmt.Printf("default") } f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755) if err != nil { log.Fatal(err) } defer f.Close() i = f switch v := i.(type) { // i的绑定的实例是*osFile类型,实现了io.ReadWriter接口,所以下面case匹配成功 case io.ReadWriter: // v是io.ReadWriter接口类型,所以可以调用Write方法 v.Write([]byte("io.ReadWriter\n")) // Type Switch Result: io.ReadWriter fmt.Println("Type Switch Result: io.ReadWriter") // 由于上一个case已经匹配,就算这个case也匹配,也不会走到这里 case *os.File: v.Write([]byte("*os.File\n")) fmt.Println("Type Switch Result: *os.File") //这里可以调用具体类型方法 v.Sync() default: fmt.Println("Type Switch Result: unknown") return }
switch v := i.(type) { // 匹配成功,v的类型就是具体类型*os.File case *os.File: v.Write([]byte("*os.File\n")) // Type Switch Result: *os.File fmt.Println("Type Switch Result: *os.File") v.Sync() //由于上一个case已经匹配,就算这个case也匹配,也不会走到这里 case io.ReadWriter: //v是io.ReadWriter接口类型,所以可以调用Write方法 v.Write([]byte("io.ReadWriter\n")) fmt.Println("Type Switch Result: io.ReadWriter") default: fmt.Println("Type Switch Result: unknown") return }
switch v := i.(type) { //多个类型,f满足其中任何一个就算匹配 case *os.File, io.ReadWriter: // 此时相当于执行力v := i ,v和i是等价的,使用v没有意义。 if v == i { // true fmt.Println(true) } default: return } }
1 2 3 4 5
# 程序输出 <nil> Type Switch Result: io.ReadWriter Type Switch Result: *os.File true
funcmain() { var a int a = 10 // the type of a is int getType(a) }
funcgetType(a interface{}) { switch a.(type) { caseint: fmt.Println("the type of a is int") casestring: fmt.Println("the type of a is string") casefloat64: fmt.Println("the type of a is float") default: fmt.Println("unknown type") } }
funcfuncName(a interface{})string { value, ok := a.(string) if !ok { fmt.Println("It is not ok for type string") return"" } fmt.Println("The value is ", value) return value }
funcmain() { // str := "123" // funcName(str) //var a interface{} //var a string = "123" var a int = 10 funcName(a) }
2)配合switch使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var t interface{} t = functionOfSomeType() switch t := t.(type) { default: fmt.Printf("unexpected type %T", t) // %T prints whatever type t has casebool: fmt.Printf("boolean %t\n", t) // t has type bool caseint: fmt.Printf("integer %d\n", t) // t has type int case *bool: fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool case *int: fmt.Printf("pointer to integer %d\n", *t) // t has type *int }
或者如下使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcsqlQuote(x interface{})string { if x == nil { return"NULL" } elseif _, ok := x.(int); ok { return fmt.Sprintf("%d", x) } elseif _, ok := x.(uint); ok { return fmt.Sprintf("%d", x) } elseif b, ok := x.(bool); ok { if b { return"TRUE" } return"FALSE" } elseif s, ok := x.(string); ok { return sqlQuoteString(s) // (not shown) } else { panic(fmt.Sprintf("unexpected type %T: %v", x, x)) } }