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

huangapple go评论77阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2017年1月23日 06:45:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/41796979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定