原文链接:

背景

asongGorune
1515159
len(str) > 200bug200len([]rune(str)) > 200
Unicode
runeUnicode
Unicode
8bitbytebyte255byteGB2312unicodeUnicode
  • 什么是字符编码?
unicodeUnicode0x6c49110110001001001152Unicode34
2Unicode4403
UnicodeUTF-8UTF-16UTF-8Unicode1 - 4UTF-8
Go

基本概念

string

人工翻译:

string8UTF-8stringnilstring
byte

写个例子验证一下:

bytestring
cannot assign to str1[1]
string

根据前面的分析,我们也可以得出我们将字符存储在字符串中时,也就是按字节进行存储的,所以最后存储的其实是一个数值。

Go
Go
GoUTF-8UTF-8GoUTF-8
Go
Gorange

运行结果:

根据运行结果我们可以得出如下结论:

ASCIIRangeUnicode
rune
rune

人工翻译:

runeint32int32
runeUnicodeGoUTF-81-4int32

答案揭晓

前面说了这么多知识点,确实有点乱了,我们现在就根据开始的那道题来做一个总结。为了方便查看,在贴一下这道题:

159

具体原因:

len()runeUnicoderuneutf-813159

贴个图,方便理解:

unicode/utf8
runeGounicode/utf8runeutf8.RuneCountInString

总结

针对全文,我们做一个总结:

UTF-8GobyteGoacsiirangeunicodeGoruneUnicodeGolen()utf8.RuneCountInStringrune

好啦,这篇文章就到这里啦,素质三连(分享、点赞、在看)都是笔者持续创作更多优质内容的动力!

推荐往期文章: