在go(golang)中传递指向字符串的指针有什么意义?

在go(golang)中传递指向字符串的指针有什么意义?

问题描述:

I was reading the following conversation about go (golang) strings. Strings in go are just a pointer to a (read-only) array and a length. Thus, when you pass them to a function the pointers are passed as value instead of the whole string. Therefore, it occurred to me, if that is true, then why are you even allowed to define as a function with a signature that takes *string as an argument? If the string is already doing plus, the data is immutable/read-only, so you can't change it anyway. What is the point in allowing go to pass pointers to strings if it already does that internally anyway?

我正在阅读以下有关 go>字符串的讨论。 go中的字符串只是一个指向(只读)数组和长度的指针。 因此,当您将它们传递给函数时,指针将作为值而不是整个字符串传递。 因此,对我来说,如果是这样,那为什么还要允许您定义为带有 * string code>作为参数的签名的函数? 如果字符串已经在执行加号操作,则数据是不可变的/只读的,因此无论如何您都无法更改它。 p> div>如果允许内部将指针传递给字符串,那有什么意义呢? p> div>

You pass a pointer to the "object" holding the string, which then you can assign something different to it.

Example: http://play.golang.org/p/Gsybc7Me-5

func ps(s *string) {
    *s = "hoo"
}
func main() {
    s := "boo"
    ps(&s)
    fmt.Println(s)
}