代码之家  ›  专栏  ›  技术社区  ›  Juan Leni

是否可以在不同的文件作用域中重用常量名称?

go
  •  1
  • Juan Leni  · 技术社区  · 6 年前

    去吧,去吧

    const {
        deviceId = 1     // I dont need this outside the file scope
    }
    
    type DeviceA struct {
        .. some fields.. 
        // I cannot make constant fields here
    }
    
    .. some methods ...
    

    酒吧去吧

    const {
        deviceId = 2      // I dont need this outside the file scope
    }
    
    type DeviceB struct {
        .. some fields ..
        // I cannot make constant fields here
    }
    
    .. some methods ...
    

    deviceId 已经重新申报。如何将这些常量保留在文件的范围内?

    如果这是一个解决方案,我不介意为常量使用某种名称空间。

    2 回复  |  直到 6 年前
        1
  •  3
  •   peterSO    6 年前

    The Go Programming Language Specification

    Packages

    Go程序是通过将包链接在一起来构建的。一个包裹 turn是由一个或多个源文件构造的 声明属于 这些元素可以导出并在另一个包中使用。

    Source file organization

    每个源文件都包含一个package子句,该子句将包定义为 它所属的,后面可能是一组空的导入 声明要使用其内容的包的声明, 变量和常量。


    在同一个包的所有文件中都可以访问属于该包的[常量]。

        2
  •  1
  •   fallaway    6 年前

    要回答您的问题:在同一范围内,在不同的文件中不可能有两个同名的常量,同一个包。

    Go中没有命名空间或文件作用域。

    但是,在同一个包中可以有两个名称相同但声明范围不同的常量:

    package main
    
    import (
        "fmt"
    )
    
    const a = 1
    
    func main() {
        const a = 2
        fmt.Println(a) // output is 2
    }
    

    https://golang.org/ref/spec#Declarations_and_scope