Go 中别名类型之间的转换是否会创建副本? [英] Does conversion between alias types in Go create copies?
问题描述
例子:
type MyString string
var s = "very long string"
var ms = MyString(s)
var s2 = string(s)
ms
或 s2
是 s
的完整副本吗(就像使用 []byte(s)代码>)?或者它们只是一个字符串结构副本(将真实值保存在指针中)?
Are ms
or s2
a full copy of s
(as it would be done with []byte(s)
)? Or they are just a string struct copies (which keeps the real value in a pointer)?
如果我们将 this 传递给函数会怎样?例如:
What if we are passing this to a function? E.g.:
func foo(s MyString){
...
}
foo(ms(s)) // do we copy s here?
推荐答案
特定规则适用于数字类型之间或字符串类型之间的(非常量)转换.这些转换可能会改变 x
的表示并产生运行时成本.所有其他转换只改变x
的类型而不改变表示.
Specific rules apply to (non-constant) conversions between numeric types or to and from a string type. These conversions may change the representation of
x
and incur a run-time cost. All other conversions only change the type but not the representation ofx
.
因此,与自定义类型的基础类型相互转换不会复制它.
So converting to and from the underlying type of your custom type does not make a copy of it.
当您将值传递给函数或方法时,会制作并传递一个副本.如果将 string
传递给函数,则只会复制和传递描述 string
的结构,因为 string
是不可变的.
When you pass a value to a function or method, a copy is made and passed. If you pass a string
to a function, only the structure describing the string
will be copied and passed, since string
s are immutable.
如果你传递一个切片也是如此(切片也是描述符).传递切片将复制切片描述符,但它会引用相同的底层数组.
Same is true if you pass a slice (slices are also descriptors). Passing a slice will make a copy of the slice descriptor but it will refer to the same underlying array.
这篇关于Go 中别名类型之间的转换是否会创建副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!