Conversions

Sometimes you want to convert a type to another type. This is possible in Go,but there are some rules. For starters, converting from one value to another isdone by operators (that look like functions: byte()) and not all conversionsare allowed.

Fromb []bytei []intr []runes stringf float32i int
To
[]byte·[]byte(s)
[]int·[]int(s)
[]rune[]rune(s)
stringstring(b)string(i)string(r)·
float32·float32(i)
intint(f)·

Valid conversions, float64 works the same as float32.

  • From a string to a slice of bytes or runes.
  1. mystring := "hello this is string"
  2. byteslice := []byte(mystring)

Converts to a byte slice, each byte contains the integer value of thecorresponding byte in the string. Note that as strings in Go are encoded inUTF-8 some characters in the string may end up in 1, 2, 3 or 4 bytes.

  1. runeslice := []rune(mystring)

Converts to an rune slice, each rune contains a Unicode code point.Every character from the string corresponds to one rune.

  • From a slice of bytes or runes to a string.
  1. b := []byte{'h','e','l','l','o'} // Composite literal.
  2. s := string(b)
  3. i := []rune{257,1024,65}
  4. r := string(i)

For numeric values the following conversions are defined:

  • Convert to an integer with a specific (bit) length: uint8(int)
  • From floating point to an integer value: int(float32). This discards thefraction part from the floating point value.
  • And the other way around: float32(int).

User defined types and conversions

How can you convert between the types you have defined yourself? We create twotypes here Foo and Bar, where Bar is an alias for Foo:

  1. type foo struct { int } // Anonymous struct field.
  2. type bar foo // bar is an alias for foo.

Then we:

  1. var b bar = bar{1} // Declare `b` to be a `bar`.
  2. var f foo = b // Assign `b` to `f`.

Which fails on the last line with:cannot use b (type bar) as type foo in assignment

This can be fixed with a conversion: var f foo = foo(b)

Note that converting structures that are not identical in their fields is moredifficult. Also note that converting b to a plain int also fails; an integeris not the same as a structure containing an integer.