O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Head First Go

Book Description

Go represents an attempt to improve on some weaknesses of traditional compiled programming languages. It de-emphasizes or removes error-prone language structures like class inheritance and exception handling. It features great concurrency support and automatic memory management (garbage collection).

Existing Go books tend to be highly technical in nature, teaching all aspects of the language regardless of their relevance to beginners. This book, rather than talking about the features of Go in abstract terms, features simple, clear examples that demonstrate Go in action, and diagrams to explain difficult concepts.

This book will not only teach developers basic language features, it will get them comfortable consulting error output, documentation, and search engines to find solutions to problems. It will teach all the conventions and techniques that employers expect an entry-level Go developer to know.

Table of Contents

  1. Table of Contents (the real thing)
  2. how to use this book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. We know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did
    6. Here’s what YOU can do to bend your brain into submission
    7. Read me
      1. It helps if you’ve done a little programming in some other language.
      2. We don’t cover every type, function, and package ever created.
      3. The activities are NOT optional.
      4. The redundancy is intentional and important.
      5. The code examples are as lean as possible.
    8. Acknowledgments
    9. O’Reilly Online Learning
  3. 1. let’s get going: Syntax Basics
    1. Ready, set, Go!
    2. The Go Playground
    3. What does it all mean?
      1. The typical Go file layout
    4. there are no Dumb Questions
    5. What if something goes wrong?
    6. Breaking Stuff is Educational!
    7. Calling functions
    8. The Println function
    9. Using functions from other packages
    10. Function return values
    11. Pool Puzzle
    12. A Go program template
    13. Strings
    14. Runes
    15. Booleans
    16. Numbers
    17. Math operations and comparisons
    18. Types
    19. Declaring variables
    20. Zero values
    21. Code Magnets
    22. Short variable declarations
    23. Breaking Stuff is Educational!
    24. Naming rules
    25. Conversions
    26. Installing Go on your computer
    27. Compiling Go code
    28. Go tools
    29. Try out code quickly with “go run”
    30. Your Go Toolbox
    31. Pool Puzzle Solution
    32. Code Magnets Solution
  4. 2. which code runs next?: Conditionals and Loops
    1. Calling methods
    2. Making the grade
    3. Comments
    4. Getting a grade from the user
    5. Multiple return values from a function or method
    6. Option 1: Ignore the error return value with the blank identifier
    7. Option 2: Handle the error
    8. Conditionals
    9. there are no Dumb Questions
    10. Logging a fatal error, conditionally
    11. Code Magnets
    12. Avoid shadowing names
    13. Converting strings to numbers
    14. Blocks
    15. Blocks and variable scope
    16. We’ve finished the grading program!
    17. Only one variable in a short variable declaration has to be new
    18. Let’s build a game
    19. Package names vs. import paths
    20. Generating a random number
    21. Getting an integer from the keyboard
    22. Comparing the guess to the target
    23. Loops
    24. Init and post statements are optional
    25. Loops and scope
    26. Breaking Stuff is Educational!
    27. Using a loop in our guessing game
    28. Skipping parts of a loop with “continue” and “break”
    29. Breaking out of our guessing loop
    30. Revealing the target
    31. The finishing touches
    32. Congratulations, your game is complete!
    33. Your Go Toolbox
    34. Code Magnets Solution
  5. 3. call me: Functions
    1. Some repetitive code
    2. Formatting output with Printf and Sprintf
    3. Formatting verbs
    4. Formatting value widths
    5. Formatting fractional number widths
    6. Using Printf in our paint calculator
    7. Declaring functions
    8. Declaring function parameters
    9. Using functions in our paint calculator
    10. Functions and variable scope
    11. Function return values
    12. Using a return value in our paint calculator
    13. Breaking Stuff is Educational!
    14. The paintNeeded function needs error handling
    15. Error values
    16. Declaring multiple return values
    17. Using multiple return values with our paintNeeded function
    18. Always handle errors!
    19. Breaking Stuff is Educational!
    20. Pool Puzzle
    21. Function parameters receive copies of the arguments
    22. Pointers
    23. Pointer types
    24. Getting or changing the value at a pointer
    25. Code Magnets
    26. Using pointers with functions
    27. Fixing our “double” function using pointers
    28. Your Go Toolbox
    29. Pool Puzzle Solution
    30. Code Magnets Solution
  6. 4. bundles of code: Packages
    1. Different programs, same function
    2. Sharing code between programs using packages
    3. The Go workspace directory holds package code
    4. there are no Dumb Questions
    5. Creating a new package
    6. Importing our package into a program
    7. Packages use the same file layout
    8. Breaking Stuff is Educational!
    9. Pool Puzzle
    10. Package naming conventions
    11. Package qualifiers
    12. Moving our shared code to a package
    13. Constants
    14. Nested package directories and import paths
    15. Installing program executables with “go install”
    16. Changing workspaces with the GOPATH environment variable
    17. Setting GOPATH
      1. On Mac or Linux systems:
      2. On Windows systems:
    18. Publishing packages
    19. Downloading and installing packages with “go get”
    20. Reading package documentation with “go doc”
    21. Documenting your packages with doc comments
    22. Viewing documentation in a web browser
    23. Serving HTML documentation to yourself with “godoc”
    24. The “godoc” server includes YOUR packages!
    25. Your Go Toolbox
    26. Pool Puzzle Solution
  7. 5. on the list: Arrays
    1. Arrays hold collections of values
    2. Zero values in arrays
    3. Array literals
    4. Functions in the “fmt” package know how to handle arrays
    5. Accessing array elements within a loop
    6. Checking array length with the “len” function
    7. Looping over arrays safely with “for...range”
    8. Using the blank identifier with “for...range” loops
    9. Getting the sum of the numbers in an array
    10. Getting the average of the numbers in an array
    11. Pool Puzzle
    12. Reading a text file
    13. Reading a text file into an array
    14. Updating our “average” program to read a text file
    15. Our program can only process three values!
    16. Your Go Toolbox
    17. Pool Puzzle Solution
  8. 6. appending issue: Slices
    1. Slices
    2. Slice literals
    3. Pool Puzzle
    4. The slice operator
    5. Underlying arrays
    6. Change the underlying array, change the slice
    7. Add onto a slice with the “append” function
    8. Slices and zero values
    9. Reading additional file lines using slices and “append”
    10. Trying our improved program
    11. Returning a nil slice in the event of an error
    12. Command-line arguments
    13. Getting command-line arguments from the os.Args slice
    14. The slice operator can be used on other slices
    15. Updating our program to use command-line arguments
    16. Variadic functions
    17. Using variadic functions
    18. Code Magnets
    19. Using a variadic function to calculate averages
    20. Passing slices to variadic functions
    21. Slices have saved the day!
    22. Your Go Toolbox
    23. Pool Puzzle Solution
    24. Code Magnets Solution
  9. 7. labeling data: Maps
    1. Counting votes
    2. Reading names from a file
    3. Counting names the hard way, with slices
    4. Maps
    5. Map literals
    6. Zero values within maps
    7. The zero value for a map variable is nil
    8. How to tell zero values apart from assigned values
    9. Removing key/value pairs with the “delete” function
    10. Updating our vote counting program to use maps
    11. Using for...range loops with maps
    12. The for...range loop handles maps in random order!
    13. Updating our vote counting program with a for...range loop
    14. The vote counting program is complete!
    15. Code Magnets
    16. Your Go Toolbox
    17. Code Magnets Solution
  10. 8. building storage: Structs
    1. Slices and maps hold values of ONE type
    2. Structs are built out of values of MANY types
    3. Access struct fields using the dot operator
    4. Storing subscriber data in a struct
    5. Defined types and structs
    6. Using a defined type for magazine subscribers
    7. Using defined types with functions
    8. Code Magnets
    9. Modifying a struct using a function
    10. Accessing struct fields through a pointer
    11. there are no Dumb Questions
    12. Pass large structs using pointers
    13. Moving our struct type to a different package
    14. A defined type’s name must be capitalized to be exported
    15. Struct field names must be capitalized to be exported
    16. Struct literals
    17. Pool Puzzle
    18. Creating an Employee struct type
    19. Creating an Address struct type
    20. Adding a struct as a field on another type
    21. Setting up a struct within another struct
    22. Anonymous struct fields
    23. Embedding structs
    24. Our defined types are complete!
    25. Your Go Toolbox
    26. Code Magnets Solution
    27. Pool Puzzle Solution
  11. 9. you’re my type: Defined Types
    1. Type errors in real life
    2. Defined types with underlying basic types
    3. Defined types and operators
    4. Pool Puzzle
    5. Converting between types using functions
    6. there are no Dumb Questions
    7. Fixing our function name conflict using methods
    8. Defining methods
    9. The receiver parameter is (pretty much) just another parameter
    10. there are no Dumb Questions
    11. A method is (pretty much) just like a function
    12. Pointer receiver parameters
    13. Breaking Stuff is Educational!
    14. Converting Liters and Milliliters to Gallons using methods
    15. Converting Gallons to Liters and Milliliters using methods
    16. Your Go Toolbox
    17. Pool Puzzle Solution
  12. 10. keep it to yourself: Encapsulation and Embedding
    1. Creating a Date struct type
    2. People are setting the Date struct field to invalid values!
    3. Setter methods
    4. Setter methods need pointer receivers
    5. Adding the remaining setter methods
    6. Adding validation to the setter methods
    7. The fields can still be set to invalid values!
    8. Moving the Date type to another package
    9. Making Date fields unexported
    10. Accessing unexported fields through exported methods
    11. Getter methods
    12. Encapsulation
    13. there are no Dumb Questions
    14. Embedding the Date type in an Event type
    15. Unexported fields don’t get promoted
    16. Exported methods get promoted just like fields
    17. Encapsulating the Event Title field
    18. Promoted methods live alongside the outer type’s methods
    19. Our calendar package is complete!
    20. Your Go Toolbox
  13. 11. what can you do?: Interfaces
    1. Two different types that have the same methods
    2. A method parameter that can only accept one type
    3. Interfaces
    4. Defining a type that satisfies an interface
    5. Concrete types, interface types
    6. Assign any type that satisfies the interface
    7. You can only call methods defined as part of the interface
    8. Breaking Stuff is Educational!
    9. Fixing our playList function using an interface
    10. there are no Dumb Questions
    11. Type assertions
    12. Type assertion failures
    13. Avoiding panics when type assertions fail
    14. Testing TapePlayers and TapeRecorders using type assertions
    15. Pool Puzzle
    16. The “error” interface
    17. there are no Dumb Questions
    18. The Stringer interface
    19. The empty interface
    20. Your Go Toolbox
    21. Pool Puzzle Solution
  14. 12. back on your feet: Recovering from Failure
    1. Reading numbers from a file, revisited
    2. Any errors will prevent the file from being closed!
    3. Deferring function calls
    4. Recovering from errors using deferred function calls
    5. Ensuring files get closed using deferred function calls
    6. Code Magnets
    7. there are no Dumb Questions
    8. Listing the files in a directory
    9. Listing the files in subdirectories (will be trickier)
    10. Recursive function calls
    11. Recursively listing directory contents
    12. Error handling in a recursive function
    13. Starting a panic
    14. Stack traces
    15. Deferred calls completed before crash
    16. Using “panic” with scanDirectory
    17. When to panic
    18. The “recover” function
    19. The panic value is returned from recover
    20. Recovering from panics in scanDirectory
    21. Reinstating a panic
    22. there are no Dumb Questions
    23. Your Go Toolbox
    24. Code Magnets Solution
  15. 13. sharing work: Goroutines and Channels
    1. Retrieving web pages
    2. Multitasking
    3. Concurrency using goroutines
    4. Using goroutines
    5. Using goroutines with our responseSize function
    6. We don’t directly control when goroutines run
    7. Code Magnets
    8. Go statements can’t be used with return values
    9. Sending and receiving values with channels
    10. Synchronizing goroutines with channels
    11. Observing goroutine synchronization
    12. Breaking Stuff is Educational!
    13. Fixing our web page size program with channels
    14. Updating our channel to carry a struct
    15. Your Go Toolbox
    16. Code Magnets Solution
  16. 14. code quality assurance: Automated Testing
    1. Automated tests find your bugs before someone else does
    2. A function we should have had automated tests for
    3. We’ve introduced a bug!
    4. Writing tests
    5. Running tests with the “go test” command
    6. Testing our actual return values
    7. More detailed test failure messages with the “Errorf” method
    8. Test “helper” functions
    9. Getting the tests to pass
    10. Test-driven development
    11. Another bug to fix
    12. there are no Dumb Questions
    13. Code Magnets
    14. Running specific sets of tests
    15. Table-driven tests
    16. Fixing panicking code using a test
    17. Your Go Toolbox
    18. Code Magnets Solution
  17. 15. responding to requests: Web Apps
    1. Writing web apps in Go
    2. Browsers, requests, servers, and responses
    3. A simple web app
    4. Your computer is talking to itself
    5. there are no Dumb Questions
    6. Our simple web app, explained
    7. Resource paths
    8. Responding differently for different resource paths
    9. First-class functions
    10. Passing functions to other functions
    11. Functions as types
    12. Pool Puzzle
    13. What’s next
    14. Your Go Toolbox
    15. Pool Puzzle Solution
  18. 16. a pattern to follow: HTML Templates
    1. A guestbook app
    2. Functions to handle a request and check errors
    3. Setting up a project directory and trying the app
    4. Making a signature list in HTML
    5. Making our app respond with HTML
    6. The “text/template” package
    7. Using the io.Writer interface with a template’s Execute method
    8. ResponseWriters and os.Stdout both satisfy io.Writer
    9. Inserting data into templates using actions
    10. Making parts of a template optional with “if” actions
    11. Repeating parts of a template with “range” actions
    12. Inserting struct fields into a template with actions
    13. Reading a slice of signatures in from a file
    14. there are no Dumb Questions
    15. A struct to hold the signatures and signature count
    16. Updating our template to include our signatures
    17. there are no Dumb Questions
    18. Letting users add data with HTML forms
    19. Responding with the HTML form
    20. Form submission requests
    21. Path and HTTP method for form submissions
    22. Getting values of form fields from the request
    23. Saving the form data
    24. HTTP redirects
    25. Let’s try it all out!
    26. Our complete app code
    27. Your Go Toolbox
  19. 17. Congratulations!: You made it to the end.
  20. 18. This isn’t goodbye
  21. A. understanding os.openfile: Opening Files
    1. Understanding os.OpenFile
    2. Passing flag constants to os.OpenFile
    3. Binary notation
    4. Bitwise operators
    5. The bitwise AND operator
    6. The bitwise OR operator
    7. Using bitwise OR on the “os” package constants
    8. Using bitwise OR to fix our os.OpenFile options
    9. Unix-style file permissions
    10. Representing permissions with the os.FileMode type
    11. Octal notation
    12. Converting octal values to FileMode values
    13. Calls to os.OpenFile, explained
    14. there are no Dumb Questions
  22. B. six things we didn’t cover: Leftovers
    1. #1 Initialization statements for “if”
    2. #2 The switch statement
    3. there are no Dumb Questions
    4. #3 More basic types
    5. #4 More about runes
    6. #5 Buffered channels
    7. #6 Further reading
  23. Index