Go — Constants and constant expressions
A Go const names a value known at compile time. Constants can be combined into another constant expression before assigning a value of a concrete type.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
package main
import "fmt"
func main() {
const unit = 3
fmt.Println(2 * unit)
}
6
Name a fixed scheduling interval
Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. An untyped integer constant can be used wherever its value is representable by the required type. The booking's slot count is an ordinary int variable.
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Run the example
Use Go 1.21 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
func main() {
const baseMinutes = 15
const slotMinutes = 2 * baseMinutes
bookedSlots := 3
fmt.Printf("%d minutes\n", bookedSlots*slotMinutes)
}
90 minutes
Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.
Try it yourself
If the base interval changes to 10 minutes, how long is the same three-slot booking?
Check your answer
Each slot now lasts 20 minutes, so the booking lasts 60 minutes.