Constants
Constants are like variables, but you can’t change their initial values. These are useful for situations where the value of a constant doesn’t need to or shouldn’t change when your code is running. You could make the argument that you could hardcode those values into the code and it would have a similar effect. Experience has shown us that while these values don’t need to change at runtime, they may need to change later. If that happens, it can be an arduous and error-prone task to track down and fix all the hardcoded values. Using a constant is a tiny amount of work now that can save you a great deal of effort later.
Constant declarations are similar to var statements. With a constant, the initial value is required. Types are optional and inferred if left out. The initial value can be a literal or a simple statement and can use the values of other constants. Like var, you can declare multiple constants in one statement. Here are the notations:
constant <name> <type> = <value> constant ( <name1> <type1> = <value1> <name2> <type2> = <value3> … <nameN> <typeN> = <valueN> )
Exercise 1.16 – constants
In this exercise, we have a performance problem: our database server is too slow. We are going to create a custom memory cache. We’ll use Go’s map collection type, which will act as the cache. There is a global limit on the number of items that can be in the cache. We’ll use one map to help keep track of the number of items in the cache. We have two types of data we need to cache: books and CDs. Both use the ID, so we need a way to separate the two types of items in the shared cache. We need a way to set and get items from the cache.
We’re going to set the maximum number of items in the cache. We’ll also use constants to add a prefix to differentiate between books and CDs. Let’s get started:
- Create a new folder and add a
main.gofile to it. - In
main.go, add themainpackage name to the top of the file:package main
- Import the packages we’ll need:
import "fmt"
- Create a constant that’s our global limit size:
const GlobalLimit = 100
- Create a
MaxCacheSizeconstant that is 10 times the global limit size:const MaxCacheSize int = 10 * GlobalLimit
- Create our cache prefixes:
const ( CacheKeyBook = "book_" CacheKeyCD = "cd_" )
- Declare a
mapvalue that has astringvalue for a key and astringvalue for its values as our cache:var cache map[string]string
- Create a function to get items from the cache:
func cacheGet(key string) string { return cache[key] } - Create a function that sets items in the cache:
func cacheSet(key, val string) { - In this function, check out the
MaxCacheSizeconstant to stop the cache going over that size:if len(cache)+1 >= MaxCacheSize { return } cache[key] = val } - Create a function to get a book from the cache:
func GetBook(isbn string) string { - Use the book cache prefix to create a unique key:
return cacheGet(CacheKeyBook + isbn) }
- Create a function to add a book to the cache:
func SetBook(isbn string, name string) { - Use the book cache prefix to create a unique key:
cacheSet(CacheKeyBook+isbn, name) }
- Create a function to get CD data from the cache:
func GetCD(sku string) string { - Use the
CDcache prefix to create a unique key:return cacheGet(CacheKeyCD + sku) }
- Create a function to add CDs to the shared cache:
func SetCD(sku string, title string) { - Use the
CDcache prefix constant to build a unique key for the shared cache:cacheSet(CacheKeyCD+sku, title) }
- Create the
main()function:func main() { - Initialize our cache by creating a
mapvalue:cache = make(map[string]string)
- Add a book to the cache:
SetBook("1234-5678", "Get Ready To Go") - Add a
CDcache prefix to the cache:SetCD("1234-5678", "Get Ready To Go Audio Book") - Get and print that
Bookfrom the cache:fmt.Println("Book :", GetBook("1234-5678")) - Get and print that
CDfrom the cache:fmt.Println("CD :", GetCD("1234-5678")) - Close the
main()function:}
- Save the file. Then, in the new folder, run the following:
go run .
The following is the output:
Figure 1.22: Output displaying the Book and CD caches
In this exercise, we used constants to define values that don’t need to change while the code is running. We declared then using a variety of notation options, some with the typeset and some without. We declared a single constant and multiple constants in a single statement.
Next, we’ll look at a variation of constants for values that are more closely related.