在Go语言中全局声明常量映射可以通过以下方式实现:

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

Declaring constant maps in golang globally

问题

在我的主函数中,我有一个与下面相同的映射:

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

然而,我想要将这个映射声明为全局变量。我该如何做到这一点?

英文:

In my main function, I have a map that is the same as follows:

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

However, I want to declare this map globally. How can I do that?

答案1

得分: 2

使用变量声明:

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

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

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

参考链接:

https://stackoverflow.com/questions/42529691/why-cant-we-declare-a-map-and-fill-it-after-in-the-const/42529986#42529986

https://stackoverflow.com/questions/13137463/declare-a-constant-array/29365828#29365828

英文:

Use a variable declaration:

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

Unlike short variable declarations (which can only occur in functions) variable declarations can be placed at the top level too.

Note however that this won't be constant, there are no map constants in Go.

See related:

https://stackoverflow.com/questions/42529691/why-cant-we-declare-a-map-and-fill-it-after-in-the-const/42529986#42529986

https://stackoverflow.com/questions/13137463/declare-a-constant-array/29365828#29365828

答案2

得分: 0

你可以将booksPresent声明在main函数之前,这样它就可以在其他函数中访问。以下是一个简单的示例程序:

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]
英文:

You can declare the booksPresent above the main so that it becomes accessible at other functions as well, here is a simple program for the same:

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)
}

Output:

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

huangapple
  • 本文由 发表于 2021年7月26日 18:56:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/68528623.html
匿名

发表评论

匿名网友

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

确定