Cast/convert int to rune in Go

Roboprog picture Roboprog · Apr 13, 2013 · Viewed 18k times · Source

Assuming I have an int64 variable (or other integer size) representing a valid unicode code-point, and I want to convert it into a rune in Go, what do I do?

In C I would have used a type cast something like:

c = (char) i;  // 7 bit ascii only

But in Go, a type assertion won't work:

c, err = rune.( i)

Suggestions?

Answer

cthom06 picture cthom06 · Apr 13, 2013

You just want rune(i). Casting is done via type(x).

Type assertions are something different. You use a type assertion when you need to go from a less specific type (like interface{}) to a more specific one. Additionally, a cast is checked at compile time, where type assertions happen at runtime.

Here's how you use a type assertion:

var (
    x interface{}
    y int
    z string
)
x = 3

// x is now essentially boxed. Its type is interface{}, but it contains an int.
// This is somewhat analogous to the Object type in other languages
// (though not exactly).

y = x.(int)    // succeeds
z = x.(string) // compiles, but fails at runtime