先看[]byte的数据结构
1 | type slice struct { |
string的数据结构
1 | type string struct { |
String不可变,[]byte可变
String默认是UTF-8编码, []byte没有
由于String类型是不可变的,如果经常需要拼接字符等,可以使用strings.Builder
方法
[]byte适合二进制传输,尤其适合文件,网络传输,因为网络就是按字节传输的
[]byte转换string
1 | data := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33} |
[]rune是int32类型,默认占四个字节,即使是ASCII字符一样,所以比string和[]byte占用的内存空间更大。
Use strings for simplicity and Unicode support,
bytes for mutability and versatility,
and runes for character-level operations.
参考
https://en.wikipedia.org/wiki/UTF-8
https://medium.com/@tyler_brewer2/bits-bytes-and-byte-slices-in-go-8a99012dcc8f
https://syslog.ravelin.com/byte-vs-string-in-go-d645b67ca7ff