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.
From | b []byte | i []int | r []rune | s string | f float32 | i int |
---|---|---|---|---|---|---|
To | ||||||
[]byte | · | []byte(s) | ||||
[]int | · | []int(s) | ||||
[]rune | []rune(s) | |||||
string | string(b) | string(i) | string(r) | · | ||
float32 | · | float32(i) | ||||
int | int(f) | · |
Valid conversions, float64
works the same as float32
.
- From a
string
to a slice of bytes or runes.
mystring := "hello this is string"
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.
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
.
b := []byte{'h','e','l','l','o'} // Composite literal.
s := string(b)
i := []rune{257,1024,65}
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
:
type foo struct { int } // Anonymous struct field.
type bar foo // bar is an alias for foo.
Then we:
var b bar = bar{1} // Declare `b` to be a `bar`.
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.