Go中的别名类型之间的转换是否创建副本? [英] Does convertion between alias types in Go create copies?

查看:127
本文介绍了Go中的别名类型之间的转换是否创建副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

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



ms s2 s 的完整副本 []字节(一个或多个))?或者他们只是一个字符串结构副本(它保留了一个指针的实际价值)?
如果我们将此函数传递给一个函数,该怎么办?例如:

  func foo(s MyString){
...
}
foo (毫秒(s))//我们在这里复制s吗?


解决方案

规范:转换:
$ b


具体规则适用于(非-constant)在数字类型之间或在字符串类型之间进行转换。这些转换可能会改变 x 的表示并导致运行时成本。 所有其他转换只会改变类型,但不会改变 x 的表示。

因此,如果转换为和来自您的自定义类型的基础类型不会创建副本。



当您将值传递给函数或方法,复制并传递。如果将字符串传递给一个函数,只会描述字符串的结构被复制并传递,因为 string 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? Eg:

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

解决方案

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

这篇关于Go中的别名类型之间的转换是否创建副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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