Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Go Programming - From Beginner to Professional
  • Table Of Contents Toc
Go Programming - From Beginner to Professional

Go Programming - From Beginner to Professional - Second Edition

By : Samantha Coyle
4.5 (14)
close
close
Go Programming - From Beginner to Professional

Go Programming - From Beginner to Professional

4.5 (14)
By: Samantha Coyle

Overview of this book

Go Programming – From Beginner to Professional is a comprehensive guide that takes your proficiency in the Go programming language from novice to expert. Starting with fundamental concepts, this book covers variables, command-line tools, and working with data before delving into advanced concepts, including error handling, interfaces, and generics, harnessing Go’s latest features through hands-on exercises. Along the way, you’ll learn to structure projects using Go modules, manage packages effectively, and master debugging techniques. As you progress, you’ll get to grips with practical application-centric aspects such as command-line programming, file manipulation, and working with SQL databases. Additionally, the book explores web server development, RESTful APIs, and utilizing the Go HTTP client to interact with web applications. Further enhancing your Go skills, you’ll learn concurrent programming, testing methodologies, Go tools, and how to deploy applications in the cloud. Throughout the book, you’ll uncover Go’s hidden gems and gain insights into time manipulation, best practices, and more. By the end of this book, you’ll have worked through practical exercises and activities that’ll equip you with the knowledge and skills needed to excel as a proficient Go developer, primed for success in real-world projects.
Table of Contents (30 chapters)
close
close
1
Part 1: Scripts
6
Part 2: Components
11
Part 3: Modules
16
Part 4: Applications
20
Part 5: Building For The Web
23
Part 6: Professional

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.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Go Programming - From Beginner to Professional
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon