英文:
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)
}
错误:
invalid operation: names[0] (type *[]string does not support indexing)
英文:
How can I pass something to a function such that it is modifiable and can be seen in the calling stack ? ( in other words how to pass a pointer or a 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
得分: 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)
}
英文:
Dereferencing a pointer has higher precedence.
Here is a code that works: 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论