type assertion doesn’t really convert the
interface type to another definite type, it just provides access to the value of the
interface type, which is usually a common requirement.
The type assertion is made via the syntax
x.(T), which will determine if the value stored in the x variable is of type T. There are two general scenarios.
- if T is not an interface type but a concrete type, then this assertion will assert whether the dynamic type of x is the same as T
- If T is an interface type, this assertion asserts whether the dynamic type of x implements T
Note: When asserting, the type of x must be
So how do you understand the phrases
T = interface and
T ! = interface?
T ! = interfaceis a normal assertion of whether x (interface) is equal to T (really type), where x must be an interface and T can be any type but a variable.
T = interfaceis not an assertion, but an assertion on interface, where x must be interface and T must be interface
As shown in the following code.
type switch is an application scenario for type assertion, which is done by asserting a variable of interface type several times to match to the real data type.