GO类型断言

    xiaoxiao2021-03-25  85

    我们知道接口可以指向任意类型对象,只要该类型实现了接口中的所有方法。

    那如何判定接口到底指向的是哪种类型的对象呢?我们可以使用类型断言来实现。

    语法:

    x.(T) 其中,x为接口变量,T为任意的类型。上面的断言语句表示   x  is not  nil  and that the value stored in  x  is of type  T

    More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

    If the type assertion holds, the value of the expression is the value stored in x and its type is T. If the type assertion is false, a run-time panic occurs. In other words, even though the dynamic type of x is known only at run time, the type of x.(T) is known to be T in a correct program.

    var x interface{} = 7 // x has dynamic type int and value 7 i := x.(int) // i has type int and value 7 type I interface { m() } func f(y I) { s := y.(string) // illegal: string does not implement I (missing method m) r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader … }

    A type assertion used in an assignment or initialization of the special form

    v, ok = x.(T) v, ok := x.(T) var v, ok = x.(T) var v, ok T1 = x.(T) yields an additional untyped boolean value. The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case.
    转载请注明原文地址: https://ju.6miu.com/read-40443.html

    最新回复(0)