如何通过引用传递以便我可以在调用函数中修改它?
How to pass by reference so I can modify it in the calling function?
我怎样才能将某些东西传递给一个函数,使其可以修改并且可以在调用堆栈中看到? (换句话说如何传递指针或引用?)
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)
解引用指针具有更高的优先级。
这是一个有效的代码: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)
}
我怎样才能将某些东西传递给一个函数,使其可以修改并且可以在调用堆栈中看到? (换句话说如何传递指针或引用?)
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)
解引用指针具有更高的优先级。
这是一个有效的代码: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)
}