本文主要研究一下golang的類型斷言golang
x.(T)
func main() { var x interface{} = 7 i := x.(int) fmt.Println(reflect.TypeOf(i)) j := x.(int32) fmt.Println(j) }
直接賦值的方式,若是斷言爲true則返回該類型的值,若是斷言爲false則產生runtime panic;j這裏賦值直接panic
輸出c#
int panic: interface conversion: interface {} is int, not int32 goroutine 1 [running]: main.main() type_assertion.go:12 +0xda exit status 2
不過通常爲了不panic,經過使用ok的方式ide
func main() { var x interface{} = 7 j, ok := x.(int32) if ok { fmt.Println(reflect.TypeOf(j)) } else { fmt.Println("x not type of int32") } }
另一種就是variable.(type)配合switch進行類型判斷指針
func main() { switch v := x.(type) { case int: fmt.Println("x is type of int", v) default: fmt.Printf("Unknown type %T!\n", v) } }
type shape interface { getNumSides() int getArea() int } type rectangle struct { x int y int } func (r *rectangle) getNumSides() int { return 4 } func (r rectangle) getArea() int { return r.x * r.y } func main() { // compile time Verify that *rectangle implement shape var _ shape = &rectangle{} // compile time Verify that *rectangle implement shape var _ shape = (*rectangle)(nil) // compile time Verify that rectangle implement shape var _ shape = rectangle{} }
輸出code
cannot use rectangle literal (type rectangle) as type shape in assignment: rectangle does not implement shape (getNumSides method has pointer receiver)
x.(T)
能夠在運行時判斷x是否爲T類型,若是直接使用賦值,當不是T類型時則會產生runtime panicvar _ someInterface = someStruct{}
能夠在編譯時期校驗某個struct或者其指針類型是否實現了某個接口