具有联合声明/赋值运算符的全局变量内联赋值和另一个未声明的变量丢失范围?
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
此Go程序将无法编译。 它将引发错误 但是,当我删除 通过在主函数中声明 global_var声明且未使用 code> p>
包main
import“ log”
var global_var int
func main (){
global_var,new_string:= returnTwoVars()
log.Println(“ new_string:” + new_string)
}
func returnTwoVars()(int,string){
返回1234 ,“ woohoo”
}
func使用GlobalVar()int {
返回global_var * 2
}
code> pre>
new_string code>并使用
:= code>运算符,而仅使用
= code>,编译器就不会发现 global_var code>是全局声明的,并在程序的其他位置使用。 我的直觉告诉我应该知道
global_var code>已经声明 p>
div>
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
.