douqi3913 2016-08-01 11:43
浏览 101
已采纳

Golang函数包含匿名作用域

Can someone give me an explanation as to when and why I would use anonymous scope inside a function? (I'm not sure what it's actually called).

I've been given some legacy code to maintain and some of the functions contain this "scope" I have not seen before:

(simplified for demonstration purposes)

func DoSomething(someBoolValue bool) string {
    if someBoolValue {
        // do some stuff
        return "yes"
    }
    {
        // weird scope code
    }
    return "no"
}

I have created a Go Playground to demonstrate some actual code (that throws an error).

  • 写回答

2条回答 默认 最新

  • dongzhanbi0027 2016-08-01 11:50
    关注

    It is called Variable scoping and shadowing:

    Go is lexically scoped using blocks:

    1-The scope of a predeclared identifier is the universe block.
    2-The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
    3-The scope of the package name of an imported package is the file block of the file containing the import declaration.
    4-The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
    5-The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
    6-The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block. 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.

    The package clause is not a declaration; the package name does not appear in any scope. Its purpose is to identify the files belonging to the same package and to specify the default package name for import declarations.

    your working sample code:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        i := 10
        {
            i := 1
            fmt.Println(i)  // 1
        }
        fmt.Println(i)  // 10
    }
    

    output:

    1
    10
    

    and see: Where can we use Variable Scoping and Shadowing in Go?

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

报告相同问题?

悬赏问题

  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决