DEV Community

Discussion on: How to access string values in Go

Collapse
 
andrewpillar profile image
Andrew Pillar • Edited

In this example, the string is converted to a slice of runes using []rune. We then loop over it and display the characters.

Iterating over a string will normally give you the runes within that string, so the conversion wouldn't be necessary, see this playground snippet as an example play.golang.org/p/LkdB8zO4Cu_d.

Also from Effective Go,

For strings, the range does more work for you, breaking out individual Unicode code points by parsing the UTF-8.

Collapse
 
robogeek95 profile image
Azeez Lukman

You're right Andrew. Thanks for pointing that out.

In addition to that, there's an even better way to access runes in a string:

package main

func main() {
    testString := "Señor"
    for index, rune := range testString {
        fmt.Printf("rune '%c' at index  %d\n", rune, index)
    }
}
Enter fullscreen mode Exit fullscreen mode

which gives:

rune 'S' at index  0
rune 'e' at index  1
rune 'ñ' at index  2
rune 'o' at index  4
rune 'r' at index  5
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andrewpillar profile image
Andrew Pillar

Yeah, %c would format it as a char, so you can avoid casting it to a string like I did with my fmt.Println call.

Collapse
 
kishanbsh profile image
Kishan B

Very cool #TIL