Convert Interface to Type: Type Assertion

· 285 words · 2 minutes read

If you’ve ever come across messages like these, you’ll no doubt have used type assertion already. This is a post explain how and why to use it.

1
cannot convert result (type interface {}) to type float64: need type assertion
1
invalid operation: myInt += 5 (mismatched types interface {} and int)

Functions and packages will at times return interface{} as a type because the type would be unpredictable or unknown to them. Returning interface allows them to pass data around without know it’s type.

Not knowing the variable’s true type however means that later down the line, many calls on this data won’t work - like the += operation in our example below. So we type assert it by placing the type in brackets after the variable name.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"

func main() {
    result := ReturnData()

    // int(result) wouldn't work at this stage:

    // Type assert, by placing brackets and type after variable name.
    // Note that we need to assign to a new variable.
    myInt := result.(int)

    // Now we can work with this, should print '10'
    myInt += 5
    fmt.Println(myInt)
}

func ReturnData() interface{} {
    return 5
}

You’ve probably noticed this doesn’t allow for much in the way of error handling. But it’s also possible to use a variant of type assertion which returns if it ran ok (like the snippet of code below).

1
2
3
4
5
myInt, ok := result.(int)
if !ok {
    log.Printf("got data of type %T but wanted int", result)
    os.Exit(1)
}

type assertion in go

There’s also a number of StackOverflow questions that explain this well.

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!