Interfaces and type assertion


(Indirajith V) #1

The book ‘Mastering Go - second edition’, has a variable declared as follows:

var myInt interface{} = 123
k, ok := myInt.(int)
if ok {
fmt.Println("Success:", k)
} 

Can any one explain a bit more on how the variable declaration ‘myInt’ works here?
My doubts are: in the above code ‘myInt’ is a variable of any type which gets type ‘int’ from the value 123. So myInt is still a variable and not an interface. Maybe its an int variable fulfilling the empty interface. But how does it works type assertion? To my understanding, myInt is not an interface just a variable. If I use int instead of interface{} at the variable declaration, the type assertion does not work. Complaining as non interface type on left.

Can anyone help me grasp this? Thank you!


(Sean Killian) #2

Hi, @Indirajith_V,

What I’ll call the “long way” to define a variable in Go is:

var myVar myType

Variables can be an interface type (io.Reader, io.Writer, etc.) or a concrete type (int, string, struct { … }, etc.). The values that get assigned to variables are always concrete types. There is no such thing as an “interface value,” the values inside of an interface variable (or struct field, function return value, etc.) are either nil if the interface has not been assigned a value or a concrete type.

In your example above, myInt is a variable whose type is interface{}. The value on the right side of the assignment (=) statement is just a constant without a type (123). Because its explicit type cannot be deduced, Go gives the constant the default type of int (see https://golang.org/ref/spec#Constants for more info).

When the statement is executed, you end up with a variable, myInt whose type is interface{} and inside of that variable is an int with the value 123.

Regarding the type assertion: That’s the way you take an interface value and try to extract its actual concrete value. The Go runtime will check at the time the program runs if the value inside of myInt is a concrete int value. If it is, k is assigned that value and ok is set to true.


(Indirajith V) #3

Thank you verymuch @skillian for you detailed explnation. Now I understand it better.