How to declare a constant map in Golang?

前端 未结 5 1912
清歌不尽
清歌不尽 2021-01-30 15:30

I am trying to declare to constant in Go, but it is throwing an error. Could anyone please help me with the syntax of declaring a constant in Go?

This is my code:

5条回答
  •  忘掉有多难
    2021-01-30 15:53

    You can create constants in many different 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 a enum constant:

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

    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.

提交回复
热议问题