gpt4 book ai didi

string - Go 中别名类型之间的转换会创建副本吗?

转载 作者:IT王子 更新时间:2023-10-29 00:52:29 26 4
gpt4 key购买 nike

例子:

type MyString string 
var s = "very long string"
var ms = MyString(s)
var s2 = string(s)

mss2s 的完整副本吗(因为它会用 []byte(s))?或者它们只是一个字符串结构副本(将实际值保存在指针中)?

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

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.

因此,与您的自定义类型的基础类型之间的转换不会复制它。

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

如果你传递一个 slice 也是如此( slice 也是描述符)。传递 slice 将创建 slice 描述符的副本,但它将引用相同的底层数组。

关于string - Go 中别名类型之间的转换会创建副本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32253768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com