1.

What do you understand by Type Assertion in Go?

Answer»

The TYPE assertion TAKES the interface value and retrieves the value of the specified explicit data type. The syntax of Type Assertion is:

t := i.(T)

Here, the statement ASSERTS that the interface value i has the CONCRETE type T and assigns the value of type T to the VARIABLE t. In case i does not have concrete type T, then the statement will result in panic.

For testing, if an interface has the concrete type, we can do it by making use of two values returned by type assertion. One value is the underlying value and the other is a bool value that tells if the assertion is completed or not. The syntax would be:

t, isSuccess := i.(T)

Here, if the interface value i have T, then the underlying value will be assigned to t and the value of isSuccess becomes true. Else, the isSuccess statement would be false and the value of t would have the zero value corresponding to type T. This ensures there is no panic if the assertion fails.



Discussion

No Comment Found