dqudtskm49788 2013-10-13 04:31
浏览 33
已采纳

Go编译器为什么不将未声明的变量视为错误?

I've been writing a test program to assist in learning Go. While doing so, I've encountered a few instances where I thought the compiler should have detected an error. I've encountered another similar situation, so I thought I should ask why this situation is not treated as an error.

Example situation :

if oError = rwfile.WriteLines(asParams, sParamsFilename); oError != nil {
    fmt.Printf("Error on write to file Params. Error = %s
", oError)
} else {
    println("Params file write OK")
}

In the example above, whether or not the variable "oError" is declared, the compiler does not indicate an error. It also works if the line contains the following when the variable is not declared (as expected):

if oError := rwfile.WriteLines(asParams, sParamsFilename); oError != nil {

If I declare the variable "oError", then ":=" does not work (as expected).

"rwfile" is a package that I have written, and the function in question starts as follows:

func WriteLines(asBuff []string, sFilename string) error { // write text file

If I create an error with the write of the file, and use "=" without declaring the variable "oError", the program works correctly and detects the non-nil "oError" variable.

So, why is use of "=" in the above not treated as an error when oError is not declared a variable?

The Go version is go1.1.2 Windows/386.

  • 写回答

2条回答 默认 最新

  • dqoag62688 2013-10-13 05:28
    关注

    This means that you have an variable named oError elsewhere in the package. (Note that this variable need not be in the same file; it could be in a different file with the same package clause.) So, when you use oError = ..., you're assigning a value to that package variable, and when you use oError := ..., you're declaring a local variable that hides the package variable. (Per the specification, "An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration." [link])

    If you try a different identifier, a unique one, you should see that the compiler indeed complains.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备