Why is it possible for me to redeclare a const in go?

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年2月19日 06:07:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/28594876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定