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条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)