【问题标题】:Declaring constant maps in golang globally在 golang 中全局声明常量映射
【发布时间】:2021-10-02 07:39:45
【问题描述】:

在我的主函数中,我有一个和下面一样的地图:

    booksPresent := map[string]bool {
        "Book One": true,
        "Book Two": true,
        "Book Three: true,
    }

但是,我想在全局范围内声明此地图。我该怎么做?

【问题讨论】:

标签: dictionary go global-variables


【解决方案1】:

使用variable declaration

var booksPresent = map[string]bool{
    "Book One":   true,
    "Book Two":   true,
    "Book Three": true,
}

short variable declarations(只能出现在函数中)不同,变量声明也可以放在顶层。

但请注意,这不会是 constant,Go 中没有映射常量。

查看相关:

Why can't we declare a map and fill it after in the const?

Declare a constant array

【讨论】:

  • 我应该将变量名的第一个字母更改为其中一个 cmets 中提到的大写字母吗?
  • @MichioKaku 如果你想从其他包中访问它,你必须这样做。如果你只想从声明包中访问它,那就不要。
  • @MichioKaku 我会完全避免导出地图,因为您的包裹的消费者可能会修改它。如果你保持小写,那么你可以确定你永远不会修改它并且它是“伪常量”。如果您需要从其他包中访问它,请考虑使用 func BookPresent(book string) bool 之类的访问器函数来保护它。
【解决方案2】:

您可以在 main 上方声明 booksPresent 以便它也可以在其他函数中访问,这是一个简单的程序:

package main

import (
    "fmt"
)

var booksPresent map[string]bool

func main() {

    booksPresent = map[string]bool{
        "Book One":   true,
        "Book Two":   true,
        "Book Three": true,
    }

    fmt.Println(booksPresent)
    trail()

}
func trail() {

    fmt.Println(booksPresent)
}

输出:

map[Book One:true Book Three:true Book Two:true]
map[Book One:true Book Three:true Book Two:true]

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 2020-06-27
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多