了解Go中的变量范围 [英] Understanding variable scope in Go

查看:80
本文介绍了了解Go中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Go specification学习语言,这些要点摘自 Declarations and scope .

I am going through the Go specification to learn the language, and these points are taken from the spec under Declarations and scope.

尽管我能够理解1-4点,但我对点56感到困惑:

Though I am able to understand points 1-4, I am confused on points 5 and 6:

  1. 内部声明的常量或变量标识符的范围 函数从ConstSpec或VarSpec(ShortVarDecl 用于简短的变量声明),并在结尾处结束 最里面的包含块.
  2. 在函数内部声明的类型标识符的范围始于 TypeSpec中的标识符,在最里面的末尾结束 包含块.
  1. 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.
  2. 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.

这是我用来理解Go中范围的代码:

This is the code which I used to understand scope in Go:

package main

import "fmt"

func main() {
    x := 42
    fmt.Println(x)
    {
        fmt.Println(x)
        y := "The test message"
        fmt.Println(y)
    }
    // fmt.Println(y) // outside scope of y
}

据此,我了解到scope of xmain函数内,并且scope of yfmt.Println(x)之后的左括号和右括号内,并且我不能在右括号之外使用y.

From this what I understand is scope of x is within the main function, and the scope of y is inside the opening and closing brackets after fmt.Println(x), and I cannot use y outside of the closing brackets.

如果我正确理解的话,4 and 5的两点都在说同样的话.所以我的问题是:

If I understand it correctly, both points 4 and 5 are saying the same thing. So my questions are:

  1. 如果他们说的是同一句话,那么两者的importance是什么? 点?

如果它们不同,可以让我知道difference吗?

If they are different, can you please let me know the difference?

推荐答案

他们用相同的规则针对两个不同的观点提出了相同的观点:第一个关于变量和常量,第二个关于类型标识符.因此,如果在块内声明类型,则作用域规则与在同一位置声明的变量相同.

They're making the same point, with the same rules, about two different things: the first is about variables and constants, the second is about type identifiers. So, if you declare a type inside a block, the same scoping rules apply as would apply to a variable declared at the same spot.

这篇关于了解Go中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆