In this part, we're going to look at Constants in Go, and how they play a role in a program.
Constants are declared like variables, but with the
const
keyword.Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the := syntax.
Consider the following code:
...
const MAX_WT = 200
func main() {
fmt.Println("Max wait time: ", MAX_WT)
}
In the above, a constant MAX_WT
is defined with a value of 200, and is available throughout the script.
The value of a constant should be known at compile time. Hence it cannot be assigned to a value returned by a function call since the function call takes place at run time.
String Constant
Any value enclosed between double quotes (eg "John Doe"), is a string constant in Go.
String constants by default are untyped:
const name = "James Bond"
Since Go is strongly typed, and all variable requires an explicit type, but the above code works, why?
Constants have a default type associated with them and they supply it if and only if a line of code demands it.
Typed String Constants
Its possible to create typed constant? Yes here's an example:
const name string = "James Bond"
Boolean Constant
Boolean constants are two untyped constants true and false. The same rules for string constants apply to booleans. Here's an example of defining boolean constants:
const published = true
Numeric Constants
Numeric constants include integers, floats and complex constants. There are some subtleties in numeric constants.
package main
import "fmt"
func main() {
const a = 5
var intVar int = a
var int32Var int32 = a
var float64Var float64 = a
var complex64Var complex64 = a
fmt.Println("intVar",intVar, "\nint32Var", int32Var, "\nfloat64Var", float64Var, "\ncomplex64Var",complex64Var)
}
Running the above you should see the following output:
$ go run main.go
intVar 5
int32Var 5
float64Var 5
complex64Var (5+0i)
That's it for constants. Here are some points you'd need to keep in mind:
- Constants can only be defined once
- Constants can be defined without a type
- Constants can be used withing the scope its being defined in
In the next part, we'd look at Functions in Go.
Have any feedback? let me know in the comments.
Cheers!
Top comments (4)
I also use often iota for constants, so it's helpful to set values in order. For example:
I'm sure you're aware of this, but for completeness for the first section, constants CAN be declared using expressions that can be evaluated at compile time.
Thanks Vinay for pointing this out.
One more thing I would like to point out,
If you have an unused variable in a program, the compiler throws an error saying "Unused variable" but not for an unused Constants.