gorune

Does the conversion from string to rune slice make a copy?


I'm teaching myself Go from a C background. The code below works as I expect (the first two Printf() will access bytes, the last two Printf() will access codepoints).

What I am not clear is if this involves any copying of data.

package main

import "fmt"

var a string

func main() {
    a = "èe"
    fmt.Printf("%d\n", a[0])
    fmt.Printf("%d\n", a[1])
    fmt.Println("")
    fmt.Printf("%d\n", []rune(a)[0])
    fmt.Printf("%d\n", []rune(a)[1])
}

In other words:

does []rune("string") create an array of runes and fill it with the runes corresponding to "string", or it's just the compiler that figures out how to get runes from the string bytes?


Solution

  • It involves a copy because:

        a = "èe"
        r := []rune(a)
        fmt.Println(len(a)) // 3 (3 bytes)
        fmt.Println(len(r)) // 2 (2 Unicode code points)