什么时候在Go中使用[] byte或字符串? [英] When to use []byte or string in Go?

查看:80
本文介绍了什么时候在Go中使用[] byte或字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经常编写Go应用程序,我发现自己可以选择使用[]bytestring.除了[]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:

  1. 一个函数返回一个新的[]byte.由于分片容量是固定的,所以什么原因不返回字符串?
  2. 默认情况下,
  3. []byte的打印效果不如string,因此我经常发现自己为了进行记录而强制转换为string.应该一直是string吗?
  4. 在添加[]byte时,始终会创建一个新的基础数组.如果要添加的数据是恒定的,为什么不应该是string?
  1. A function returns a new []byte. Since the slice capacity is fixed, what reason is there to not return a string?
  2. []byte are not printed as nicely as string by default, so I often find myself casting to string for logging purposes. Should it always have been a string?
  3. When prepending []byte, a new underlying array is always created. If the data to prepend is constant, why should this not be a string?

推荐答案

我的建议是在处理文本时默认使用字符串.但是,如果满足以下条件之一,则使用[] 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆