Constants can be confusing and easy to misuse in Go if you are coming from an untyped language. In this article we will learn what constants are, and when it is best to make use of them.
Most of the points I make here apply to general-purpose programming languages as a whole, but by focusing specifically on Go we can dive a bit deeper and come up with some good rules of thumb.
Go vs Javascript
Many languages have constants, typically denoted by the keyword const.
In go and javascript alike they are declared as such:
const frameRate = 60
The interesting thing about constants in Go is that they:
- 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
By contrast, in javascript they:
- (Mostly) can’t change, but you can of course run your javascript program, it will just break at runtime
- Can be mutated (but not reassigned), if they are of a type that has inner workings that change, like an array or object
- Can be assigned using calculated values at runtime, but can’t be re-assigned.
Must be assigned at compile time
Constants in Go must be assigned before the program runs, that is, when the program compiles using go build. Constants can rely on the value of other constants, but not on runtime calculations. For example:
const seconds = 120
const minutes = seconds / 60
Is fine because both values can be known before the program runs. The following will not work:
func addMinutes(minutes int) {
const more = minutes + 60
return more
}
This won’t work because “ more ” relies on a runtime variable, “ minutes “. Keep in mind that this would work in javascript, because the only rule with constants in javascript is that they can’t be re-assigned.
Constants are Faster
The Go compiler doesn’t need to worry about a constant changing its value, so it can swap every instance of the const with an unchanging number. This makes constants slightly faster.
Only some types can be constant
Numeric, boolean, and string types can all be made constant. This includes things like runes, floats, integers, and even custom types that are based on valid underlying types. For example:
type myString string
const lane myString = "wagslane"
Other types like arrays, slices, and maps can not be declared as constant. This makes sense because those types are essentially just pointers, which are addresses of mutable data.
By contrast, in javascript anything can be made constant. Arrays can be constant, and an array can have its elements mutated, or it can be enlarged or shrunk. The only safety the const provides is that the variable can’t be explicitly reassigned.
Constants are untyped unless assigned
In Go, variables can have their typed inferred:
thisIsAString := "wagslane"
Constants on the other hand get an untyped flag
const thisIsAnUntypedString = "wagslane"
An untyped string behaves mostly like a string. That is, its a string type, but doesn’t have a Go value of type string. In order to give it the official Go type of string, it must be declared:
const thisIsATypedString string = "wagslane"
To read more about untyped constants checkout:
https://blog.golang.org/constants#TOC_4.
How should I use constants in Go?
Anything that can be a constant should be a constant. By declaring a variable constant you get the following benefits:
- Less bugs. No risk of accidentally modifying the value later by accident
- Faster runtime
- Easier readability. Any variable that is not declared const is read by other developers as “safe to mutate”.
Additionally, constants don’t follow the same rule of thumb that normal variables do when being declared in the global scope. There is nothing wrong with declaring global constants. Granted, if the constant is only used in one place, it may make sense to declare it there. The point however remains: it isn’t dangerous to declare constants globally.
The danger of global variables is obvious: if you create a global variable then all functions using that variable become stateful. Each invocation of that function has the potential to behave differently.
Hopefully this helps you understand a bit more about constants and when to use them. Thanks for reading!
By Lane Wagner @wagslane
Download Qvault: https://qvault.io
Star our Github: https://github.com/q-vault/qvault
The post Constants in Go vs Javascript, and When to Use Them appeared first on Qvault.
Top comments (0)