Constants can be confusing and easy to misuse in Go if you are coming from an untyped language. Let’s take a look at some of the nuanced details of how they work in Go. It’s probably unsurprising, but Go’s constants are almost nothing like JavaScript’s bastardized version of the concept.

Go vs JavaScript

Many programming languages support constants, often denoted by the keyword const.

Go and JavaScript both declare new constants in the same way:

const frameRate = 60

Constants in Go

  • Must be able to be assigned at compile time. The value of a const can’t be the result of a runtime calculation.
  • Run faster because the compiler can make specific optimizations.
  • Cannot change. The compiler will not allow them to be re-assigned.
  • Only work with some types. Arrays, Slices, Maps, Structs, etc… can’t be made constant
  • Are not normal Go types unless explicitly assigned as such

#languages #clean code #engineering practices #golang #javascript #compile #const #constant #global #go #golang #javascript

The Nuances of Constants in Go; Go Isn't JavaScript
2.55 GEEK