package main import "fmt" func main() { s := "hello" freq := make(map[rune]int) for _, ch := range s { freq[ch]++ } fmt.Println(freq) }
In Go, when printing a map with rune keys, the keys are shown as their integer Unicode code points. For example, 'h' is 104, 'e' is 101, 'l' is 108, and 'o' is 111. The frequency counts are correct for the string "hello".
Using rune as the map key is best because it represents Unicode code points, allowing correct counting of all characters including multi-byte ones. byte only covers ASCII, and string keys would be inefficient for single characters.
package main import "fmt" func main() { s := "abc" freq := make(map[string]int) for _, ch := range s { freq[ch]++ } fmt.Println(freq) }
The map is declared with string keys but the loop variable ch is a rune. You cannot use a rune directly as a string key without conversion, so this causes a compilation error.
package main import "fmt" func main() { s := "a😊a" freq := make(map[rune]int) for _, ch := range s { freq[ch]++ } fmt.Println(freq) }
The string contains 'a' twice (Unicode 97) and the emoji 😊 once (Unicode 128522). The map prints rune keys as integers, so the output shows counts accordingly.
package main import "fmt" func main() { s := "GoLang 2024!" freq := make(map[rune]int) for _, ch := range s { if ch != ' ' { freq[ch]++ } } fmt.Println(len(freq)) }
The string "GoLang 2024!" without spaces has these unique characters: G, o, L, a, n, g, 2, 0, 4, ! — total 10 unique characters.
