英文:
Global variable inline assignment with combined declaration/assignment operator and another undeclared variable losing scope?
问题
这个Go程序无法编译。它会抛出错误global_var declared and not used。
package main
import "log"
var global_var int
func main() {
global_var, new_string := returnTwoVars()
log.Println("new_string: " + new_string)
}
func returnTwoVars() (int, string) {
return 1234, "woohoo"
}
func usesGlobalVar() int {
return global_var * 2
}
然而,当我通过在主函数中声明new_string并简单地使用=而不是:=操作符来消除对它的需要时,编译器不会对在程序的其他地方使用已经全局声明的global_var有任何问题。我的直觉告诉我它应该知道global_var已经被声明了。
英文:
This Go program will not compile. It throws the error global_var declared and not used
package main
import "log"
var global_var int
func main() {
global_var, new_string := returnTwoVars()
log.Println("new_string: " + new_string)
}
func returnTwoVars() (int, string) {
return 1234, "woohoo"
}
func usesGlobalVar() int {
return global_var * 2
}
However, when I remove the need for using the := operator by declaring new_string in the main function and simply using =, the compiler doesn't have a problem with seeing that global_var is declared globally and being used elsewhere in the program. My intuition tells me that it should know that global_var is declared already
答案1
得分: 14
编译器对于main函数外的global_var没有抱怨。它只对在main函数中新创建的未使用的global_var抱怨。你可以通过查看go提到的行号来验证这一点。
你可以尝试一个空程序,其中包含一个在任何函数外部没有被引用的global_var:没有任何问题。当然,usesGlobalVar函数确实引用了实际的全局符号,但与你在main中创建的那个没有任何关系。
英文:
The compiler doesn't complain about the global_var outside main. It only complains about the newly created global_var in main that you don't use. Which you can check by looking at the line number that go mentions.
You can try an empty program with a global_var outside any function that nobody references: no problems there. And of course, the usesGlobalVar function that does reference the actual global symbol has nothing to do with the one you create in main.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论