Golang interface ducktype and type assertion

The interface{} type in Golang is like the duck type in python. If it walks like a duck, it’s a duck – the type is determined by an attribute of the variable. This duck typing support in python often leaves one searching for the actual type of the object that a function takes or returns; but with richer names, or a naming convention, one gets past this drawback. Golang tries to implement a more limited and stricter duck typing: the programmer can define the type of a variable as an interface{}, but when it comes time to determine the type of the duck, one must assert it explicitly. This is called type assertion. During type assertion the progream can receive an error indicating that there was a type mismatch.

explicit ducktype creation example:

var myVariableOfDuckType interface{} = “thisStringSetsMyVarToTypeString”

var mySecondVarOfDuckType interface{} = 123 // sets type to int

ducktype assertion

getMystring, isOk := myVariableOfDuckType.(string) // isOk is true, assertion to string passed

getMystring, isOk := mySecondVarOfDuckType.(string) // isOk is false, assertion to string failed

In python, int(123) and int(“123”) both return 123.

In Golang, int(mySecondVarOfDuckType) will not return 123, even though the value actually happens to be an int. It will instead return a “type assertion error”.

cannot convert val (type interface {}) to type int: need type assertion

This is very odd. The type here is interface, not int – the “int subtype” is held within the “interface type”. The concrete type can be printed with %T and can be used in a type assertion switch.

GO Hello world – 3 types of declarations of an int

package main
import "fmt"
func main() {
 i:=1
 var j int
 j = 2
 var k int = 5;
 fmt.Println("Hello, world.", i, j, k)
}

GO Function call syntax

package main
import "fmt"

func main() {
 first := 2
 second := 3
 firstDoubled, secondDoubled := doubleTwo(first, second)
 fmt.Println("Numbers: ", first, second)
 fmt.Println("Doubling: ", firstDoubled, secondDoubled)
 fmt.Println("Tripling: ", triple(first), triple(second))
}

//function with named return variables
func doubleTwo(a, b int) (aDoubled int, bDoubled int) {
 aDoubled = a * 2
 bDoubled = b * 2
return
}

//function without named return variables
func triple(a int) int {
 return (a * 3)
}

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s