什么时候在Go中使用[] byte或字符串? [英] When to use []byte or string in Go?
问题描述
经常编写Go应用程序,我发现自己可以选择使用[]byte
或string
.除了[]byte
的明显可变性之外,我该如何确定要使用哪一个?
Frequently in writing Go applications, I find myself with the choice to use []byte
or string
. Apart from the obvious mutability of []byte
, how do I decide which one to use?
我有几个用例作为示例:
I have several use cases for examples:
- 一个函数返回一个新的
[]byte
.由于分片容量是固定的,所以什么原因不返回字符串?
默认情况下, -
[]byte
的打印效果不如string
,因此我经常发现自己为了进行记录而强制转换为string
.应该一直是string
吗? - 在添加
[]byte
时,始终会创建一个新的基础数组.如果要添加的数据是恒定的,为什么不应该是string
?
- A function returns a new
[]byte
. Since the slice capacity is fixed, what reason is there to not return a string? []byte
are not printed as nicely asstring
by default, so I often find myself casting tostring
for logging purposes. Should it always have been astring
?- When prepending
[]byte
, a new underlying array is always created. If the data to prepend is constant, why should this not be astring
?
推荐答案
我的建议是在处理文本时默认使用字符串.但是,如果满足以下条件之一,则使用[] byte:
My advice would be to use string by default when you're working with text. But use []byte instead if one of the following conditions applies:
-
[]字节的可变性将大大减少所需的分配数量.
The mutability of a []byte will significantly reduce the number of allocations needed.
您正在处理使用[] byte的API,并且避免转换为字符串将简化您的代码.
You are dealing with an API that uses []byte, and avoiding a conversion to string will simplify your code.
这篇关于什么时候在Go中使用[] byte或字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!