英文:
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/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/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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论