我有这段文字,希望将其放入一个字节切片中:
s := "There are these two young fish swimming along and they happen to meet an older fish swimming the other way"
如果我写
b := []byte("There are these two young fish swimming along and they happen to meet an older fish swimming the other way")
据我理解,在运行时,这将会:
- 创建一个包含内存中的值的字符串
- 创建一个字节切片
- 将字符串内容复制到字节切片中(必要时重新分配内存)
我可以将每个字符串值转换为其ASCII等效项并直接创建字节切片:
b := []byte{84, 104, ... }
虽然这不是很易读。
我知道这个例子有点琐碎,而且大多数计算机可以迅速完成这项工作,但我对此很感兴趣。编译器会解释[]byte("blah")
并在编译时将其转换为高效的字节片吗?如果字符串包含非ASCII字符,最佳解决方案是否会改变?
for _, chr := range str {...}
循环这样的东西处理utf8;您的程序可能不需要特别注意处理utf-8。 - twotwotwo