英文:
Inputting variable name into functions
问题
我对Go语言还不太熟悉,但我可以帮你将这段代码翻译成函数形式。以下是翻译好的代码:
func changeColor(varName string) string {
if varName == "yellow" {
varName = "black"
} else {
varName = "yellow"
}
return varName
}
你可以将这个函数放在你的代码中,然后通过调用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
if varName == yellow {
varName = black
} else {
varName = yellow
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论