聊聊golang的類型斷言

本文主要研究一下golang的類型斷言golang

類型斷言

x.(T)
  • 斷言x不爲nil且x爲T類型
  • 若是T不是接口類型,則該斷言x爲T類型
  • 若是T類接口類型,則該斷言x實現了T接口

實例1

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")
    }
}

switch type

另一種就是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)
    }
}

判斷struct是否實現某個接口

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 panic
  • 使用var _ someInterface = someStruct{}能夠在編譯時期校驗某個struct或者其指針類型是否實現了某個接口

doc

相關文章
相關標籤/搜索