go

golang how does the rune() function work


I came across a function posted online that used the rune() function in golang, but I am having a hard time looking up what it is. I am going through the tutorial and inexperienced with the docs so it is hard to find what I am looking for.

Specifically, I am trying to see why this fails...

fmt.Println(rune("foo"))

and this does not

fmt.Println([]rune("foo"))

Solution

  • rune is a type in Go. It's just an alias for int32, but it's usually used to represent Unicode points. rune() isn't a function, it's syntax for type conversion into rune. Conversions in Go always have the syntax type() which might make them look like functions.

    The first bit of code fails because conversion of strings to numeric types isn't defined in Go. However conversion of strings to slices of runes/int32s is defined like this in language specification:

    Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string. [golang.org]

    So your example prints a slice of runes with values 102, 111 and 111