将字符串作为参数传递时正在复制什么?

发布于 2025-01-11 21:45:50 字数 677 浏览 1 评论 0原文

在 Golang 中,一切都是按值传递的。如果我“直接”传递一个数组(而不是通过指针传递它),那么在函数中所做的任何修改都将在函数外部找到

func f(a []int) {
    a[0] = 10
}
func main() {
    a := []int{2,3,4}
    f(a)
    fmt.Println(a)
}

Output: [10 3 4]

这是因为,据我所知,数组(除其他外)构成了指针到底层数据数组。

除非我弄错了(请参阅此处)字符串也构成(与“ len”对象)的一个指向底层数据的指针(一个unsafe.Pointer)。因此,我期待与上面相同的行为,但显然,我错了。

func f(s string) {
    s = "bar"
}
func main() {
    s := "foo"
    f(s)
    fmt.Println(s)
}

Output: "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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若无相欠,怎会相见 2025-01-18 21:45:50

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文