Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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:




// Golang program to illustrate 
// the concept of type assertions
package main
  
import (
    "fmt"
)
  
// main function
func main() {
      
    // an interface that has 
    // a string value
    var value interface{} = "GeeksforGeeks"
      
    // retrieving a value
    // of type string and assigning
    // it to value1 variable
    var value1 string = value.(string)
      
    // printing the concrete value
    fmt.Println(value1)
      
    // this will panic as interface
    // does not have int type
    var value2 int = value.(int)
      
    fmt.Println(value2)
}

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:




// Golang program to show type
// assertions with error checking
package main
  
import (
    "fmt"
)
  
// main function
func main() {
      
    // an interface that has 
    // an int value
    var value interface{} = 20024
      
    // retrieving a value
    // of type int and assigning
    // it to value1 variable
    var value1 int = value.(int)
      
    // printing the concrete value
    fmt.Println(value1)
      
    // this will test if interface
    // has string type and
    // return true if found or
    // false otherwise
    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!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!