[Go] A puzzle for string type

Natan
1 min readApr 1, 2021

Puzzle

s := "Hi你好"
fmt.Println(len(s))
for i, c := range s {
fmt.Println(i, int(s[i]) == int(c))
}
  1. What’s the length of string s?

Answer: 8

2. How many times will the loop be executed?

Answer: 4

In Go, string is represented in UTF-8 bytes. Its length is the length of UTF-8 byte array. “你好” are two Chinese characters, most Chinese characters can be presented with two bytes (UTF-16), however, it will require 3 bytes in UTF-8 s1110xxxx 10yyyyyy 10 zzzzzz. Hence, the length is 2 + 3*2 = 8.

To loop string s, it should be 4 times as there are only 4 characters. c is of rune type which is int32 and can represent any unicode characters.

The most interesting is thati is not 0,1,2,3 , it’s 0,1,2,5 instead. Because there are 8 bytes, the 4th char is composited of s[5], s[6], s[7].

Here’s the program link https://play.golang.org/p/zuuzh4y_uQQ

--

--

Natan

Senior Software Engineer. Used to work with Tencent, Alibaba and Amazon.