How to declare a permanent card in golang

I am new to golang. I am trying to declare constant in go. But this is a mistake. Can someone help me with the syntax for declaring a constant in go?

This is my code:

const romanNumeralDict map[int]string = { 1000: "M", 900 : "CM", 500 : "D", 400 : "CD", 100 : "C", 90 : "XC", 50 : "L", 40 : "XL", 10 : "X", 9 : "IX", 5 : "V", 4 : "IV", 1 : "I", } 

This is mistake

 # command-line-arguments ./Roman_Numerals.go:9: syntax error: unexpected { 
+49
go
Aug 20 '13 at 18:15
source share
4 answers

Your syntax is incorrect. To make an alphabetic map (as pseudo-constant), you can do:

 var romanNumeralDict = map[int]string{ 1000: "M", 900 : "CM", 500 : "D", 400 : "CD", 100 : "C", 90 : "XC", 50 : "L", 40 : "XL", 10 : "X", 9 : "IX", 5 : "V", 4 : "IV", 1 : "I", } 

Inside func you can declare it as:

 romanNumeralDict := map[int]string{ ... 

And in Go there is no such thing as a permanent map. More information can be found here .

Try it on the Go Playground.

+65
Aug 20 '13 at 18:21
source share

You can create constants in many ways:

 const myString = "hello" const pi = 3.14 // untyped constant const life int = 42 // typed constant (can use only with ints) 

You can also create an enumeration constant:

 const ( First = 1 Second = 2 Third = 4 ) 

You cannot create constants for maps, arrays and write to the efficient version :

Constants in Go are the same constants. They are created by compiling time, even if they are defined as local functions, and there can only be numbers, characters (runes), strings, or Booleans. Due to the limitation of compilation time, the expressions that define them must be constant expressions evaluated by the compiler. For example, 1 <3 is a constant expression, whereas math.Sin (math.Pi / 4) does not occur because the math.Sin function call must occur at run time.

+13
Apr 24 '15 at 1:42
source share

You can emulate a card with closing:

 package main import ( "fmt" ) // http://stackoverflow.com/a/27457144/10278 func romanNumeralDict() func(int) string { // innerMap is captured in the closure returned below innerMap := map[int]string{ 1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I", } return func(key int) string { return innerMap[key] } } func main() { fmt.Println(romanNumeralDict()(10)) fmt.Println(romanNumeralDict()(100)) dict := romanNumeralDict() fmt.Println(dict(400)) } 

Try on the Go Playground

+3
Dec 13 '14 at 8:55
source share

As indicated above, defining a map as a constant is not possible. But you can declare a global variable, which is a structure containing a map.

Initialization will look like this:

 var romanNumeralDict = struct { m map[int]string }{m: map[int]string { 1000: "M", 900: "CM", //YOUR VALUES HERE }} func main() { d := 1000 fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000]) } 
+1
03 Sep '16 at 14:30
source share



All Articles