Does conversion between alias types in Go create copies?

huangapple go评论70阅读模式
英文:

Does conversion between alias types in Go create copies?

问题

示例:

类型 MyString string 
var s = "非常长的字符串"
var ms = MyString(s)
var s2 = string(s)

mss2s 的完全副本吗(就像使用 []byte(s) 一样)?还是它们只是字符串结构的副本(将实际值保存在指针中)?

如果我们将其传递给一个函数会怎样?例如:

func foo(s MyString){
  ...
}
foo(ms(s))  // 这里我们会复制 s 吗?
英文:

Example:

type MyString string 
var s = "very long string"
var ms = MyString(s)
var s2 = string(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)?

What if we are passing this to a function? E.g.:

func foo(s MyString){
  ...
}
foo(ms(s))  // do we copy s here?

答案1

得分: 13

[规范:转换:]

针对数值类型之间的(非常量)转换或与字符串类型之间的转换,有特定的规则。这些转换可能会改变x的表示并产生运行时开销。所有其他转换只改变x的类型而不改变其表示。

因此,将自定义类型转换为其底层类型或将其底层类型转换为自定义类型并不会创建副本。

当将值传递给函数或方法时,会创建并传递一个副本。如果将string传递给函数,只会复制和传递描述string的结构,因为string是不可变的。

如果传递一个切片(切片也是描述符),同样适用。传递切片会复制切片描述符,但它将引用相同的底层数组。

英文:

Spec: Conversions:

> 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 of x.

So converting to and from the underlying type of your custom type does not make a copy of it.

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 strings 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.

huangapple
  • 本文由 发表于 2015年8月27日 23:37:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/32253768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定