英文:
What is being copied when passing a string as parameter?
问题
在Golang中,一切都是按值传递的。如果我直接传递一个数组(而不是通过指针传递),那么在函数中进行的任何修改都会在函数外部被发现。
func f(a []int) {
a[0] = 10
}
func main() {
a := []int{2,3,4}
f(a)
fmt.Println(a)
}
输出:[10 3 4]
这是因为,据我理解,数组包括(除其他内容外)指向底层数据数组的指针。
除非我弄错了(参见这里),字符串也包括(与"len"对象一起)指向底层数据的指针(一个unsafe.Pointer
)。因此,我原以为会有与上述类似的行为,但显然我错了。
func f(s string) {
s = "bar"
}
func main() {
s := "foo"
f(s)
fmt.Println(s)
}
输出:"foo"
这里字符串发生了什么?似乎在将字符串作为参数传递时,底层数据被复制了。
相关问题:当我们不希望函数修改字符串时,出于性能原因,是否仍建议通过指针传递大字符串?
英文:
In Golang, everything is passed by value. If I pass an array "directly" (as opposed as passing it by pointer), then any modification made in the function will be found outside of it
func f(a []int) {
a[0] = 10
}
func main() {
a := []int{2,3,4}
f(a)
fmt.Println(a)
}
Output: [10 3 4]
This is because, to my understanding, an array constitutes (among other things) of a pointer to the underlying data array.
Unless I am mistaken (see here) strings also constitute (along with a "len" object) of a pointer (a unsafe.Pointer
) to the underlying data. Hence, I was expecting the same behaviour as above but, apparently, I was wrong.
func f(s string) {
s = "bar"
}
func main() {
s := "foo"
f(s)
fmt.Println(s)
}
Output: "foo"
What is happening here with the string? Seems like the underlying data is being copied when the string is passed as argument.
Related question: When we do not wish our function to modify the string, is it still recommended to pass large strings by pointer for performance reasons?
答案1
得分: 4
一个string
包含两个值:指向数组的指针和字符串的长度。当你将字符串作为参数传递时,这两个值会被复制,而不是底层的数组。
除了使用unsafe
之外,没有其他方法可以修改字符串的内容。当你将*string
传递给一个函数,并且该函数修改了字符串时,该函数只是将字符串指向不同的数组。
英文:
A string
has two values in it: pointer to an array, and the string length. When you pass string as an argument, those two values are copied, not the underlying array.
There is no way to modify the contents of string other than using unsafe
. When you pass a *string
to a function and that function modifies the string, the function simply modifies the string to point to a different array.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论