doushansu9012 2014-07-08 22:09
浏览 544
已采纳

在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?

  • 写回答

1条回答 默认 最新

  • douyou7797 2014-07-08 22:21
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?