doushi3202 2015-09-30 16:55
浏览 19
已采纳

在函数中输入变量名

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

if varName == yellow {
    varName = black
} else {
    varName = yellow
}
  • 写回答

1条回答 默认 最新

  • dongyi1429 2015-09-30 17:33
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?