How to declare a constant map in Golang?

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

How to declare a constant map in Golang?

问题

我正在尝试在Go语言中声明一个常量,但是它报错了。

这是我的代码:

  1. const myMap = map[int]string{
  2. 1: "one",
  3. 2: "two",
  4. 3: "three",
  5. }

这是错误信息:

  1. map[int]string{...}(类型为map[int]string的值)不是常量
英文:

I am trying to declare to constant in Go, but it is throwing an error.

This is my code:

  1. const myMap = map[int]string{
  2. 1: "one",
  3. 2: "two",
  4. 3: "three",
  5. }

This is the error

  1. map[int]string{…} (value of type map[int]string) is not constant

答案1

得分: 250

在Go语言中,不幸的是,map不能被声明为const。你可以使用var关键字将其声明为普通变量,如下所示:

  1. var myMap = map[int]string{
  2. 1: "one",
  3. 2: "two",
  4. 3: "three",
  5. }

在函数内部,你可以使用短变量声明语法进行声明:

  1. func main() {
  2. myMap := map[int]string{
  3. 1: "one",
  4. 2: "two",
  5. 3: "three",
  6. }
  7. }

在Go playground上试一试。

英文:

In Go, a map unfortunately cannot be const. You can declare it as a regular variable like this with the var keyword:

  1. var myMap = map[int]string{
  2. 1: "one",
  3. 2: "two",
  4. 3: "three",
  5. }

Inside a function, you may declare it with the short assignment syntax:

  1. func main() {
  2. myMap := map[int]string{
  3. 1: "one",
  4. 2: "two",
  5. 3: "three",
  6. }
  7. }

Try it out on the Go playground.

答案2

得分: 35

你可以用多种方式创建常量:

  1. const myString = "hello"
  2. const pi = 3.14 // 无类型常量
  3. const life int = 42 // 有类型常量(只能用于整数)

你还可以创建枚举常量:

  1. const (
  2. First = 1
  3. Second = 2
  4. Third = 4
  5. )

你不能创建映射和数组的常量,这在《Effective Go》中有所说明:

在Go中,常量就是常量。它们在编译时创建,即使在函数中定义为局部变量,也只能是数字、字符(符文)、字符串或布尔值。由于编译时的限制,定义常量的表达式必须是常量表达式,可以由编译器计算出结果。例如,1<<3是一个常量表达式,而math.Sin(math.Pi/4)不是,因为调用math.Sin的函数需要在运行时发生。

英文:

You can create constants in many different ways:

  1. const myString = &quot;hello&quot;
  2. const pi = 3.14 // untyped constant
  3. const life int = 42 // typed constant (can use only with ints)

You can also create a enum constant:

  1. const (
  2. First = 1
  3. Second = 2
  4. Third = 4
  5. )

You can not create constants of maps, arrays and it is written in effective go:

> Constants in Go are just that—constant. They are created at compile
> time, even when defined as locals in functions, and can only be
> numbers, characters (runes), strings or booleans. Because of the
> compile-time restriction, the expressions that define them must be
> constant expressions, evaluatable by the compiler. For instance, 1<<3
> is a constant expression, while math.Sin(math.Pi/4) is not because the
> function call to math.Sin needs to happen at run time.

答案3

得分: 18

你可以使用闭包来模拟一个映射:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // http://stackoverflow.com/a/27457144/10278
  6. func romanNumeralDict() func(int) string {
  7. // innerMap 被闭包捕获,返回的闭包函数中使用了 innerMap
  8. innerMap := map[int]string{
  9. 1000: "M",
  10. 900: "CM",
  11. 500: "D",
  12. 400: "CD",
  13. 100: "C",
  14. 90: "XC",
  15. 50: "L",
  16. 40: "XL",
  17. 10: "X",
  18. 9: "IX",
  19. 5: "V",
  20. 4: "IV",
  21. 1: "I",
  22. }
  23. return func(key int) string {
  24. return innerMap[key]
  25. }
  26. }
  27. func main() {
  28. fmt.Println(romanNumeralDict()(10))
  29. fmt.Println(romanNumeralDict()(100))
  30. dict := romanNumeralDict()
  31. fmt.Println(dict(400))
  32. }

在 Go playground 上试一试

英文:

You may emulate a map with a closure:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. // http://stackoverflow.com/a/27457144/10278
  6. func romanNumeralDict() func(int) string {
  7. // innerMap is captured in the closure returned below
  8. innerMap := map[int]string{
  9. 1000: &quot;M&quot;,
  10. 900: &quot;CM&quot;,
  11. 500: &quot;D&quot;,
  12. 400: &quot;CD&quot;,
  13. 100: &quot;C&quot;,
  14. 90: &quot;XC&quot;,
  15. 50: &quot;L&quot;,
  16. 40: &quot;XL&quot;,
  17. 10: &quot;X&quot;,
  18. 9: &quot;IX&quot;,
  19. 5: &quot;V&quot;,
  20. 4: &quot;IV&quot;,
  21. 1: &quot;I&quot;,
  22. }
  23. return func(key int) string {
  24. return innerMap[key]
  25. }
  26. }
  27. func main() {
  28. fmt.Println(romanNumeralDict()(10))
  29. fmt.Println(romanNumeralDict()(100))
  30. dict := romanNumeralDict()
  31. fmt.Println(dict(400))
  32. }

Try it on the Go playground

答案4

得分: 4

根据Siu Ching Pong - Asuka Kenji的建议,以下是一个更合理的函数,它使用了地图类型,而没有在函数周围添加包装器:

  1. // romanNumeralDict 返回 map[int]string 字典,由于返回值始终相同,它提供了伪常量的输出,可以以类似地图的方式引用。
  2. var romanNumeralDict = func() map[int]string {
  3. return map[int]string{
  4. 1000: "M",
  5. 900: "CM",
  6. 500: "D",
  7. 400: "CD",
  8. 100: "C",
  9. 90: "XC",
  10. 50: "L",
  11. 40: "XL",
  12. 10: "X",
  13. 9: "IX",
  14. 5: "V",
  15. 4: "IV",
  16. 1: "I",
  17. }
  18. }
  19. func printRoman(key int) {
  20. fmt.Println(romanNumeralDict()[key])
  21. }
  22. func printKeyN(key, n int) {
  23. fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
  24. }
  25. func main() {
  26. printRoman(1000)
  27. printRoman(50)
  28. printKeyN(10, 3)
  29. }

play.golang.org上尝试一下。

英文:

And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

  1. // romanNumeralDict returns map[int]string dictionary, since the return
  2. // value is always the same it gives the pseudo-constant output, which
  3. // can be referred to in the same map-alike fashion.
  4. var romanNumeralDict = func() map[int]string { return map[int]string {
  5. 1000: &quot;M&quot;,
  6. 900: &quot;CM&quot;,
  7. 500: &quot;D&quot;,
  8. 400: &quot;CD&quot;,
  9. 100: &quot;C&quot;,
  10. 90: &quot;XC&quot;,
  11. 50: &quot;L&quot;,
  12. 40: &quot;XL&quot;,
  13. 10: &quot;X&quot;,
  14. 9: &quot;IX&quot;,
  15. 5: &quot;V&quot;,
  16. 4: &quot;IV&quot;,
  17. 1: &quot;I&quot;,
  18. }
  19. }
  20. func printRoman(key int) {
  21. fmt.Println(romanNumeralDict()[key])
  22. }
  23. func printKeyN(key, n int) {
  24. fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
  25. }
  26. func main() {
  27. printRoman(1000)
  28. printRoman(50)
  29. printKeyN(10, 3)
  30. }

Try this at play.golang.org.

答案5

得分: 0

我知道这段代码看起来不太好看,但你可以使用匿名结构体和闭包来实现类似于常量映射的功能:

  1. type MapGet[T any, V any] func(T) (V, bool)
  2. var (
  3. myMap = struct {
  4. Get MapGet[int, string]
  5. }{
  6. Get: func(mp map[int]string) MapGet[int, string] {
  7. return func(key int) (string, bool) {
  8. v, found := mp[key]
  9. return v, found
  10. }
  11. }(map[int]string{
  12. 1: "one",
  13. 2: "two",
  14. 3: "three",
  15. }),
  16. }
  17. )
  18. func main() {
  19. v, _ := myMap.Get(1)
  20. fmt.Println(v)
  21. }

你可以在这里查看代码:https://goplay.tools/snippet/SrAMRsBOPn9

英文:

I know this is not the nicest looking code, but you can achieve somewhat of a constant map-like thing using anonymous structs and closures:

Voila!

  1. type MapGet[T any, V any] func(T) (V, bool)
  2. var (
  3. myMap = struct {
  4. Get MapGet[int, string]
  5. }{
  6. Get: func(mp map[int]string) MapGet[int, string] {
  7. return func(key int) (string, bool) {
  8. v, found := mp[key]
  9. return v, found
  10. }
  11. }(map[int]string{
  12. 1: &quot;one&quot;,
  13. 2: &quot;two&quot;,
  14. 3: &quot;three&quot;,
  15. }),
  16. }
  17. )
  18. func main() {
  19. v, _ := myMap.Get(1)
  20. fmt.Println(v)
  21. }

https://goplay.tools/snippet/SrAMRsBOPn9

答案6

得分: -5

如上所述,无法将地图定义为常量。但是,您可以声明一个全局变量,该变量是一个包含地图的结构体。

初始化的代码如下所示:

  1. var romanNumeralDict = struct {
  2. m map[int]string
  3. }{m: map[int]string {
  4. 1000: "M",
  5. 900: "CM",
  6. //在这里添加您的值
  7. }}
  8. func main() {
  9. d := 1000
  10. fmt.Printf("键(%d)的值为:%s", d, romanNumeralDict.m[1000])
  11. }
英文:

As stated above to define a map as constant is not possible.
But you can declare a global variable which is a struct that contains a map.

The Initialization would look like this:

  1. var romanNumeralDict = struct {
  2. m map[int]string
  3. }{m: map[int]string {
  4. 1000: &quot;M&quot;,
  5. 900: &quot;CM&quot;,
  6. //YOUR VALUES HERE
  7. }}
  8. func main() {
  9. d := 1000
  10. fmt.Printf(&quot;Value of Key (%d): %s&quot;, d, romanNumeralDict.m[1000])
  11. }

huangapple
  • 本文由 发表于 2013年8月21日 02:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/18342195.html
匿名

发表评论

匿名网友

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

确定