将变量名输入函数中

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

Inputting variable name into functions

问题

我对Go语言还不太熟悉,但我可以帮你将这段代码翻译成函数形式。以下是翻译好的代码:

  1. func changeColor(varName string) string {
  2. if varName == "yellow" {
  3. varName = "black"
  4. } else {
  5. varName = "yellow"
  6. }
  7. return varName
  8. }

你可以将这个函数放在你的代码中,然后通过调用changeColor(varName)来实现将原始变量的值更改为新值的功能。希望这样能帮到你!

英文:

I'm pretty new to Go, and I'd like to make this snippet into a function.

Basically, I would like to know if there is a possible way to pass a variable name into a function call so if I called:

changeColor(varName)

It would run, and then assign a new value to the original variable, which was inputted into the function call.

Hopefully this makes sense, and thanks in advance

  1. if varName == yellow {
  2. varName = black
  3. } else {
  4. varName = yellow
  5. }

答案1

得分: 3

你可以通过阅读不同编程语言使用的不同评估策略来了解这个概念。在Go语言中,你可以通过指针来实现你所期望的行为。

如果没有使用指针,通常你传递的是变量的副本。而使用指针时,你传递的是值在内存中的位置的副本。这意味着函数可以修改它所了解的位置上的实际值。

这里有一个示例来演示你所解释的内容:

http://play.golang.org/p/ufrEjmXwmB

请记住,在实际程序中,这可能不是最佳的做法。但如果你只是为了学习,那就试试吧。可以尝试一下传递指向指针的指针等等 :p

英文:

You can learn about the concept in general by reading up on different Evaluation Strategies that programming languages employ. In Go you can achieve the behavior you are looking for with pointers.

Without pointers you are usually passing around copies of your variable. With pointers, you are passing a copy of the location of the value in memory. This means the function can then modify the actual value at the location is has learned about.

Here is an example that does what you explained:

http://play.golang.org/p/ufrEjmXwmB

Keep in mind this is probably not the best way to do this in a real program. If the point is to just learn though, then go for it. Try playing around with passing pointers to pointers and so on :p

huangapple
  • 本文由 发表于 2015年10月1日 00:55:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/32871719.html
匿名

发表评论

匿名网友

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

确定