英文:
Why is it possible for me to redeclare a const in go?
问题
例如
package main
import "fmt"
const s string = "constant"
func main() {
const s = 0
fmt.Println(s)
}
实际上打印出
0
然而,在 main 函数之前,我将其声明为 "constant"。
我原以为你无法更改常量。如果不是这样的话,为什么不使用其他类型呢?
英文:
For exmaple
package main
import "fmt"
const s string = "constant"
func main() {
const s = 0
fmt.Println(s)
}
actually prints
0
Yet I declared it as "constant" before main.
I thought you were unable to change a constant. If this is not the case, why not use other types?
答案1
得分: 8
这是main
作用域中的一个新常量。它不会改变外部作用域中的常量。可以查阅有关"shadowing"的信息。
这个程序很好地演示了这一点:
package main
import "fmt"
func main() {
const a = 0
fmt.Println(a)
{
const a = 1
fmt.Println(a)
}
fmt.Println(a)
}
输出结果如下:
0
1
0
英文:
It's a new constant in the scope of main
. It doesn't change the one in the outer scope. Look up shadowing.
This program demonstrates it well:
package main
import "fmt"
func main() {
const a = 0
fmt.Println(a)
{
const a = 1
fmt.Println(a)
}
fmt.Println(a)
}
The output is as follows:
0
1
0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论