Global variable inline assignment with combined declaration/assignment operator and another undeclared variable losing scope?

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

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.

huangapple
  • 本文由 发表于 2014年5月9日 06:10:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/23553446.html
匿名

发表评论

匿名网友

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

确定