What is a rune in Go and how is it different from a regular byte?
I just started learning Go and came across a strange thing — the `rune` type. It seems to be an integer, but why have a separate type? I'm trying to work with strings and noticed that when I get a character by index, I get strange numbers instead of letters.
Here's an example that confused me:
```go
package main
import "fmt"
func main() {
s := "Привет, мир!"
fmt.Println(s[0]) // Prints 208, not 'П'
fmt.Println(string(s[0])) // Prints 'Ð', not 'П'
}
```
Why does this happen? I expected `s[0]` to give me the first character of the string. But instead I get some garbage.
I read that I need to use `rune`, but I don't understand how exactly. I tried this:
```go
r := []rune(s)
fmt.Println(string(r[0])) // Now prints 'П'
```
This works, but I don't understand why.
No answers yet.
Log in to leave an answer