如何将某些内容传递给函数,使其可以修改并可以在调用堆栈中看到? (换句话说,如何传递指针或引用?)
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)
答案 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)
}