Go – x.(T) Type Assertions

An interface variable can store any non-interface concrete value, which is really useful when you are not sure about your variable type.

Because interface variable can be any kind of concrete value, we need a good way to determine the REAL value type of interface variable is to use Type Assertions from Go.

Here is a simple example:

package main
import "fmt"
func main() {
  var x interface{} = 10

  v, ok := x.(int)
  fmt.Println(v, ok)
}

v, ok := x.(int) will return two values; the first value will be the actual value, and second value will be bool which can tell you if the interface variable x matches the type int or not.

You can also use switch case to determine the variable type:

package main
import "fmt"
func main() {
  var x interface{} = 10

  switch v := x.(type) {
    case int:
      fmt.Println("int data", v)
    case string:
      fmt.Println("string data", v)
    default:
      fmt.Println("I don't like your type", v)
  }
}

Type assertions can only be used on interface variable. If you use Type assertions on non-interface value, you will get invalid message:

package main
import "fmt"
func main() {
  var x int = 10

  switch v := x.(type) {
    case int:
      fmt.Println("int data", v)
    case string:
      fmt.Println("string data", v)
    default:
      fmt.Println("I don't like your type", v)
  }
}
// It will tells you: cannot type switch on non-interface value x (type int)

The reason for getting this error message is because it is not possible for x to store a value of type T if you are not using interface. You can get more detail from Type Assertions.

Related Articles:

Advertisements

One thought on “Go – x.(T) Type Assertions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s