Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go Programming - From Beginner to Professional

You're reading from   Go Programming - From Beginner to Professional Learn everything you need to build modern software using Go

Arrow left icon
Product type Paperback
Published in Mar 2024
Publisher Packt
ISBN-13 9781803243054
Length 680 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Samantha Coyle Samantha Coyle
Author Profile Icon Samantha Coyle
Samantha Coyle
Arrow right icon
View More author details
Toc

Table of Contents (30) Chapters Close

Preface 1. Part 1: Scripts
2. Chapter 1: Variables and Operators FREE CHAPTER 3. Chapter 2: Command and Control 4. Chapter 3: Core Types 5. Chapter 4: Complex Types 6. Part 2: Components
7. Chapter 5: Functions – Reduce, Reuse, and Recycle 8. Chapter 6: Don’t Panic! Handle Your Errors 9. Chapter 7: Interfaces 10. Chapter 8: Generic Algorithm Superpowers 11. Part 3: Modules
12. Chapter 9: Using Go Modules to Define a Project 13. Chapter 10: Packages Keep Projects Manageable 14. Chapter 11: Bug-Busting Debugging Skills 15. Chapter 12: About Time 16. Part 4: Applications
17. Chapter 13: Programming from the Command Line 18. Chapter 14: File and Systems 19. Chapter 15: SQL and Databases 20. Part 5: Building For The Web
21. Chapter 16: Web Servers 22. Chapter 17: Using the Go HTTP Client 23. Part 6: Professional
24. Chapter 18: Concurrent Work 25. Chapter 19: Testing 26. Chapter 20: Using Go Tools 27. Chapter 21: Go in the Cloud 28. Index 29. Other Books You May Enjoy

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:

  1. Create a new folder and add a main.go file to it.
  2. In main.go, add the main package name to the top of the file:
    package main
  3. Import the packages we’ll need:
    import "fmt"
  4. Create a constant that’s our global limit size:
    const GlobalLimit = 100
  5. Create a MaxCacheSize constant that is 10 times the global limit size:
    const MaxCacheSize int = 10 * GlobalLimit
  6. Create our cache prefixes:
    const (
      CacheKeyBook = "book_"
      CacheKeyCD = "cd_"
    )
  7. Declare a map value that has a string value for a key and a string value for its values as our cache:
    var cache map[string]string
  8. Create a function to get items from the cache:
    func cacheGet(key string) string {
      return cache[key]
    }
  9. Create a function that sets items in the cache:
    func cacheSet(key, val string) {
  10. In this function, check out the MaxCacheSize constant to stop the cache going over that size:
      if len(cache)+1 >= MaxCacheSize {
        return
      }
      cache[key] = val
    }
  11. Create a function to get a book from the cache:
    func GetBook(isbn string) string {
  12. Use the book cache prefix to create a unique key:
      return cacheGet(CacheKeyBook + isbn)
    }
  13. Create a function to add a book to the cache:
    func SetBook(isbn string, name string) {
  14. Use the book cache prefix to create a unique key:
      cacheSet(CacheKeyBook+isbn, name)
    }
  15. Create a function to get CD data from the cache:
    func GetCD(sku string) string {
  16. Use the CD cache prefix to create a unique key:
      return cacheGet(CacheKeyCD + sku)
    }
  17. Create a function to add CDs to the shared cache:
    func SetCD(sku string, title string) {
  18. Use the CD cache prefix constant to build a unique key for the shared cache:
      cacheSet(CacheKeyCD+sku, title)
    }
  19. Create the main() function:
    func main() {
  20. Initialize our cache by creating a map value:
      cache = make(map[string]string)
  21. Add a book to the cache:
      SetBook("1234-5678", "Get Ready To Go")
  22. Add a CD cache prefix to the cache:
      SetCD("1234-5678", "Get Ready To Go Audio Book")
  23. Get and print that Book from the cache:
      fmt.Println("Book :", GetBook("1234-5678"))
  24. Get and print that CD from the cache:
      fmt.Println("CD :", GetCD("1234-5678"))
  25. Close the main() function:
    }
  26. 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

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.

You have been reading a chapter from
Go Programming - From Beginner to Professional - Second Edition
Published in: Mar 2024
Publisher: Packt
ISBN-13: 9781803243054
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image