Type Assertions in Golang
Last Updated :
22 Jun, 2020
Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type. Basically, it is used to remove the ambiguity from the interface variables.
Syntax:
t := value.(typeName)
where value is a variable whose type must be an interface, typeName is the concrete type we want to check and underlying typeName value is assigned to variable t.
Example 1:
Output:
GeeksforGeeks
panic: interface conversion: interface {} is string, not int
In the above code, since the value interface does not hold an int type, the statement triggered panic and the type assertion fails. To check whether an interface value holds a specific type, it is possible for type assertion to return two values, the variable with typeName value and a boolean value that reports whether the assertion was successful or not. This is shown in the following example:
Example 2:
package main
import (
"fmt"
)
func main() {
var value interface{} = 20024
var value1 int = value.( int )
fmt.Println(value1)
value2, test := value.(string)
if test {
fmt.Println( "String Value found!" )
fmt.Println(value2)
} else {
fmt.Println( "String value not found!" )
}
}
|
Output:
20024
String value not found!