golang:[] byte(string)vs [] byte(* string) [英] golang: []byte(string) vs []byte(*string)
问题描述
我很好奇为什么Golang不提供 []字节(*字符串)
方法。从性能的角度来看,不会出现 [] byte(string)
作为输入参数的副本并增加更多成本(尽管这看起来很奇怪,因为字符串是不可变的,为什么copy他们)?
我是Go的新手,希望能澄清一下。 div
[] byte(something)
不是函数(或方法)调用,而是 conversion 。
类型转换本身不会复制该值。然而,将一个字符串
转换为一个 []字节
是需要的,因为结果字节片是 mutable ,如果不能创建副本,则可以修改/更改字符串
值( string
),它是不可变的,它必须是规格:字符串类型部分规定:
字符串是不可变的:一旦创建,就不可能改变字符串的内容。 / p>
请注意,当 string
<=> [] byte
转换不会复制,因为编译器将其优化为远离。当有证据证明不可变的字符串
不能/不会最终被修改时,这些是罕见的和硬编码的情况。
这样一个例子就是从键值为 string
的映射中查找一个值,然后用 [] byte
,转换为字符串
当然( $ b $ $ p $ code> key:= [] byte(some key)
var m map [string] T
// ...
v,ok:= m [string(key)] //复制key在这里被优化掉
另一个优化是对显式转换的字符串
的字节到字节片段:
s:=something
for i,v:= range [] byte( s){//复制s被优化掉
// ...
}
(请注意,如果没有转换,范围的会遍历
符文
s而不是其UTF8编码的字节。)
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)?
I'm new to Go and would appreciate any clarification.
[]byte("something")
is not a function (or method) call, it's a type conversion.
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.
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.
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
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
// ...
}
(Note that without the conversion the for range
would iterate over the rune
s of the string and not over its UTF8-encoded bytes.)
这篇关于golang:[] byte(string)vs [] byte(* string)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!