golang: []byte(string) vs []byte(*string) [英] golang: []byte(string) vs []byte(*string)

查看:29
本文介绍了golang: []byte(string) vs []byte(*string)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么 Golang 不提供 []byte(*string) 方法.从性能的角度来看,不会 []byte(string) 复制输入参数并增加更多成本(尽管这看起来很奇怪,因为字符串是不可变的,为什么要复制它们)?

I'm curious as why Golang doesn't provide a []byte(*string) method. From a performance perspective, wouldn't []byte(string) make a copy of the input argument and add more cost (though this seems odd since strings are immutable, why copy them)?

我是 Go 的新手,希望得到任何澄清.

I'm new to Go and would appreciate any clarification.

推荐答案

[]byte("something") 不是函数(或方法)调用,它是类型 转换.

[]byte("something") is not a function (or method) call, it's a type conversion.

类型转换本身"不会复制值.但是,将 string 转换为 []byte 确实可以,并且需要这样做,因为结果字节切片是 可变的,并且如果副本将不是,你可以修改/改变 string 值(string 的内容),它是 immutable,它必须是 规范:字符串类型部分规定:

The type conversion "itself" does not copy the value. Converting a string to a []byte however does, and it needs to, because the result byte slice is mutable, and if a copy would not be made, you could modify / alter the string value (the content of the string) which is immutable, it must be as the Spec: String types section dictates:

字符串是不可变的:一旦创建,就不可能更改字符串的内容.

Strings are immutable: once created, it is impossible to change the contents of a string.

请注意,很少有 string <=> []byte 转换不会复制的情况,因为它已被编译器远离"优化.当有证据证明不可变的 string 不能/不会被修改时,这些是罕见的硬编码"情况.

Note that there are few cases when string <=> []byte conversion does not make a copy as it is optimized "away" by the compiler. These are rare and "hard coded" cases when there is proof an immutable string cannot / will not end up modified.

这样的例子是从键类型为 string 的映射中查找值,并且您使用 []byte 索引映射,转换为 string 当然(source):

Such an example is looking up a value from a map where the key type is string, and you index the map with a []byte, converted to string of course (source):

key := []byte("some key")

var m map[string]T
// ...
v, ok := m[string(key)]  // Copying key here is optimized away

另一种优化是对显式转换为字节片的 string 的字节进行范围:

Another optimization is when ranging over the bytes of a string that is explicitly converted to a byte slice:

s := "something"
for i, v := range []byte(s) { // Copying s is optimized away
    // ...
}

(请注意,如果没有转换,for range 将遍历字符串的 runes 而不是其 UTF8 编码字节.)

(Note that without the conversion the for range would iterate over the runes of the string and not over its UTF8-encoded bytes.)

这篇关于golang: []byte(string) vs []byte(*string)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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