如何通过引用传递,以便我可以在调用函数中修改它?

时间:2017-01-22 22:45:21

标签: go pass-by-reference

如何将某些内容传递给函数,使其可以修改并可以在调用堆栈中看到? (换句话说,如何传递指针或引用?)

package main

import (
    "os/exec"
    "fmt"
)

func process(names *[]string) {
    fmt.Print("Pre process", names)
    names[1] = "modified"
}

func main() {    
    names := []string{"leto", "paul", "teg"}
    process(&names)

    fmt.Print("Post process", names)
}

Error:
invalid operation: names[0] (type *[]string does not support indexing)

1 个答案:

答案 0 :(得分:1)

取消引用指针具有更高的优先级 这是一个有效的代码:https://play.golang.org/p/9Bcw_9Uvwl

package main

import (
    "fmt"
)

func process(names *[]string) {
    fmt.Println("Pre process", *names)
    (*names)[1] = "modified"
}

func main() {
    names := []string{"leto", "paul", "teg"}
    process(&names)
    fmt.Println("Post process", names)
}