Paste / convert int to rune in Go

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

In C, I would use a cast type something like:

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

But in Go, a type statement will not work:

 c, err = rune.( i) 

Suggestions?

+4
source share
2 answers

You just need rune(i) . Casting is done through type(x) .

Type statements are something else. You use a type assertion when you need to go from a less defined type (like interface{} ) to a more specific one. In addition, the listing is checked at compile time, where type statements occur at run time.

Here's how you use a type statement:

 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 
+12
source

In Go, you want to do a conversion.

Conversions

Transformations are expressions of the form T(x) , where T is a type and x is an expression that can be converted to type T

 Conversion = Type "(" Expression ")" . 

The variable x value can be converted to type T in any of these cases:

  • x assigned to T
  • x type and T have the same base types.
  • x type and T are unnamed pointer types, and their base pointer types have the same base types.
  • x type and T are integers or floating point.
  • x type and T are complex types.
  • x is an integer or has the type []byte or []rune , and T is a string type.
  • x is a string, and T is []byte or []rune .

You want to convert x , of type int , int32 or int64 , to T type rune , an alias for type int32 . x and T are integer types.

Therefore, T(x) allowed and written rune(x) , for your example, c = rune(i) .

+2
source

All Articles