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