dongnu4254 2014-05-08 22:10 采纳率: 100%
浏览 8
已采纳

具有联合声明/赋值运算符的全局变量内联赋值和另一个未声明的变量丢失范围?

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条回答 默认 最新

  • dongxiao3694 2014-05-08 22:19
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算