https://github.
com/martensonbj/fem-intro-to-go
(Hi! Fire this GitHub repository up in your browser for reference 🤘)
INTRO TO GO
FROM THE OTHER SIDE
(A LOVE STORY)
01. MEET CUTE
THE SETUP
01. SETUP: WHY
WHY GO AT F.E.M?
01. SETUP: ABOUT ME https://github.com/martensonbj/fem-intro-to-go
(For real…you’re going to need this)
ABOUT ME
Brenna Martenson
(gopherize.me)
@martenson_bj
01. SETUP: THE PLAN
WHAT TODAY LOOKS LIKE
▸ Brief Introduction
▸ Installation
▸ Basic Syntax & Structure
▸ Build some Go apps
▸ Brief look at concurrency
01. SETUP: SLIDES
SLIDES
What information is available on the slides?
01_folder/file.md
01. SETUP: SLIDES 01_folder/code/file.go
SECTION NUMBER + BREADCRUMBS FILES I AM REFERENCING
(green means something actionable!)
(grey means lecture notes!)
SLIDES CURRENT SECTION TITLE
(the repo structure will match the section structure)
01. SETUP: HISTORY
HISTORY
01. SETUP: HISTORY
BEFORE GO
It was 2007 It was Google It was C++
Performance and scalability were hot topics
(Unsurprisingly, Google had become a large, difficult to maintain codebase)
‣ 1. Fast compile times
‣ 2. Ease of development
‣ 3. Fast execution
01. SETUP: HISTORY
ENTER: GO
‣ Fast compile time ‣ Lightweight type system
‣ Lots in common with C ‣ Concurrency
‣ Reduces complexity of C ‣ Automatic garbage collection
‣ Wicked fast build time ‣ Strict dependencies
‣ Convention
01. SETUP: INSTALLATION
INSTALLATION
01. SETUP: THINGS YOU NEED
THINGS YOU NEED
▸ An IDE of some kind (I’ll be on VSCode)
▸ Option Two: Go Playground
▸ A Terminal Window
▸ Your Favorite Browser (I’ll be in Chrome)
01. SETUP: EXERCISE 0 01_setup/exercise_0.md
Reminder: ^^ this file path lives here:
github.com/martensonbj/fem-intro-to-go)
(5 MINUTES)
EXERCISE #0
INSTALLING GO
01. SETUP: INSTALLING GO 01_setup/exercise_0.md
INSTALLING GO
▸ Install Go
▸ golang.org/dl
01. SETUP: INSTALLING GO golang.com/dl 01_setup/exercise_0.md
1. Verify Go was installed: 2. Add these to your .bash_profile:
3. Verify those updates:
4. Create a workspace
‣ Navigate to your $GOPATH (ie: /Users/brennamartenson)
‣ mkdir go && cd go
‣ mkdir src && cd src
‣ git clone https://github.com/martensonbj/fem-intro-to-go.git
‣ cd fem-intro-to-go && go run main.go
01. SETUP: DOCUMENTATION
DOCUMENTATION
01. SETUP: DOCUMENTATION golang.org
DOCUMENTATION & RESOURCES
01. SETUP: EXERCISE 1A 01_setup/exercise_1a.md
(5 MINUTES)
EXERCISE #1A
FIND STUFF
02. FIRST DATES ARE
AWKWARD
LETS GET THE WEIRD PARTS OUT OF THE WAY
02. INTRODUCTION: THE WEIRD PARTS
TYPING
▸ Strongly typed ▸ Dynamically typed
▸ String, Float, Int, Byte, ▸ Variables can change
Struct… ▸ Typescript
02. INTRODUCTION: THE WEIRD PARTS
STRUCTURES
▸ Structs, Pointers, Methods, ▸ ES6 Classes (kind of)
Interfaces ▸ Define behavior and
▸ Define behavior and attributes
attributes
02. INTRODUCTION: THE WEIRD PARTS
ERROR HANDLING
▸ Explicit ▸ Built in
▸ Sad path won’t handle ▸ You'll get yelled at
itself regardless
02. INTRODUCTION: THE WEIRD PARTS
MULTI-TASKING
▸ Multi-Threaded ▸ Single-Threaded
▸ Concurrency, ▸ Callbacks, async await,
Goroutines, Sync sagas, sadness
02. INTRODUCTION: THE WEIRD PARTS
OPINIONATED-NESS
▸ Strong Opinions ▸ Fluid Opinions
▸ Convention, built in ▸ Subjective to the mood
tooling and linters that day
02. INTRODUCTION: ANATOMY 02_introduction/anatomy.md
ANATOMY (OF A FILE)
02. INTRODUCTION: ANATOMY 02_introduction/anatomy.md
( pronounced “fumpt” 🙄 )
02. INTRODUCTION: PRINTING 02_introduction/printing.md
PRINTING
fmt.Println()
02. INTRODUCTION: PRINTING 02_introduction/printing.md
PLAY.GOLANG.ORG
Goal: Experiment with printing
02. INTRODUCTION: PRINTING 02_introduction/printing.md
Print fmt.Print() - Prints output to the stdout console
- Returns number of bytes and an error
fmt.Println() - (The error is generally not worried about
fmt.Printf()
- Prints the output to an external source (file, browser)
Fprint fmt.Fprint() - Does not print to the stdout console
fmt.Fprintln() - Returns number of bytes, and any write errors
fmt.Fprintf()
- Stores output on a character buffer
Sprint fmt.Sprint() - Does not print to stdout console
fmt.Sprintln() - Returns the string you want to print
fmt.Sprintf()
02. INTRODUCTION: EXERCISE 2A 02_introduction/exercise_2a.md
(5 MINUTES)
EXERCISE #2A
HELLO WORLD+
03. BASIC SYNTAX
03. LETS TALK
BASIC SYNTAX
03. BASIC SYNTAX: TYPES 03_basic_syntax/types.md
TYPES
03. BASIC SYNTAX: TYPES 03_basic_syntax/types.md
Name Type Name Examples
1 2 44 770
INTEGER int int8 int16 int32 int64
uint uint8 uint26 uint32 uint64 var age int = 21
float32 float64
1.5 3.14 2100
FLOAT var gpa float64 = 4.0
string “Pancakes”
STRING var plant string = “ficus”
bool
true false
BOOLEAN && || ! < <= >= == != var canDrink bool = age > 21
03. BASIC SYNTAX: TYPES 03_basic_syntax/types.md
PLAY.GOLANG.ORG
‣ Identify the type of a variable
‣ Convert types
03. BASIC SYNTAX: VARIABLES 03_basic_syntax/variables.md
VARIABLES
03. BASIC SYNTAX: VARIABLES 03_basic_syntax/variables.md
I’ll be here: 03_BASIC_SYNTAX/CODE/VARIABLES.GO
But if you want, you can go here: PLAY.GOLANG.ORG
03. BASIC SYNTAX: CONTROL STRUCTURES 03_basic_syntax/ctrl_structures.md
‣ If statements
‣ For loops
CONTROL ‣ Switch statements
STRUCTURES
03. BASIC SYNTAX: CONTROL STRUCTURES/IF 03_basic_syntax/ctrl_structures.md
IF STATEMENTS
03_BASIC_SYNTAX/CODE/IFS.GO
03. BASIC SYNTAX: CONTROL STRUCTURES 03_basic_syntax/ctrl_structures.md
SWITCH STATEMENTS
03_BASIC_SYNTAX/CODE/SWITCH.GO
03. BASIC SYNTAX: CONTROL STRUCTURES 03_basic_syntax/ctrl_structures.md
FOR LOOPS
03_BASIC_SYNTAX/CODE/FOR.GO
03: BASIC SYNTAX: EXERCISE 3A 03_basic_syntax/exercise_3a.md
(7 MINUTES)
EXERCISE #3A
CONTROL STRUCTURES
04. COMPLEX STRUCTURES
04. OK BUT I WANT TO
KNOW MORE ABOUT
MORE COMPLEX STRUCTURES
YOU
04. COMPLEX STRUCTURES: FUNCTIONS 04_complex_structures/functions.md
FUNCTIONS
04. COMPLEX STRUCTURES: FUNCTIONS 04_complex_structures/functions.md
FUNCTIONS
04_COMPLEX_STRUCTURES/CODE/FUNCTIONS.GO
04. COMPLEX STRUCTURES: FUNCTIONS 04_complex_structures/exercise_4a.md
(5 MINUTES)
EXERCISE #4A
FUNCTIONS
04. COMPLEX STRUCTURES: FUNCTIONS 04_complex_structures/functions.md
VARIADIC FUNCTION
04. COMPLEX STRUCTURES: FUNCTIONS 04_complex_structures/exercise_4b.md
(5 MINUTES)
EXERCISE #4B
VARIADIC FUNCTIONS
04. COMPLEX STRUCTURES: ARRAYS 04_complex_structures/arrays.md
ARRAYS
04. COMPLEX STRUCTURES: ARRAYS 04_complex_structures/arrays.md
ARRAYS
NOTE: Length is part of the type definition.
[5]float64 != [6]float64
04. COMPLEX STRUCTURES: ARRAYS 04_complex_structures/arrays.md
ARRAYS
> _TRY IT_
> Copy line 9 from this example into the Go playground
> Print out the variable `scores` as is.
> What do you see?
04. COMPLEX STRUCTURES: ARRAYS 04_complex_structures/arrays.md
ARRAYS: DEFINING VALUES
> Try It
> Using range, iterate over the array of
scores printing each value
> What error do you get?
04. COMPLEX STRUCTURES: ARRAYS 04_complex_structures/arrays.md
ARRAYS: DEFINING VALUES
Needing to know the exact length of an array every time you need one seems problematic.
ENTER: THE SLICE
04. COMPLEX STRUCTURES: SLICES 04_complex_structures/slices.md
SLICES (+ MAKE)
Segments of an underlying array Must be associated with space in memory
04. COMPLEX STRUCTURES: SLICES 04_complex_structures/slices.md
MAKE
According to the docs:
Make "Initializes and allocates space in memory for a slice, map, or channel.”
04_complex_structures/code/slices.go
> Try It
> Print the results of each of these variables
in your go program (or the go playground).
> What happens?
04. COMPLEX STRUCTURES: SLICES 04_complex_structures/slices.md
SLICES
fruitArray := [5]string{"banana", "pear", "apple", "kumquat", “peach"}
var splicedFruit []string = fruitArray[1:3] // ==> [“pear”, “apple”]
splicedFruit
pointer
length capacity = 4
length = 2
capacity banana pear apple kumquat peach fruitArray
0 1 2 3 4
04. COMPLEX STRUCTURES: SLICES 04_complex_structures/slices.md
SLICES
04_COMPLEX_STRUCTURES/CODE/SLICES.GO
‣ Modifying the length of a slice
‣ Append
‣ Copy
04. COMPLEX STRUCTURES: MAPS
MAPS
04. COMPLEX STRUCTURES: MAPS 04_complex_structures/maps.md
MAPS
> _TRY IT_
> Add this code into a go file or playground
> Add a third email and run the program
> What happens? What are we missing?
04. COMPLEX STRUCTURES: EXERCISE 4 04_complex_structures/exercise_4c.md
(7 MINUTES)
EXERCISE #4C
COMPLEX STRUCTURES: SUMMARY
05. TOOLKIT
05. SO WHERE ARE
YOU FROM?
THE GO TOOLKIT & PACKAGES
05. TOOLKIT: GO TOOLS 05_toolkit/tools.md
GO TOOLS &
COMMANDS
05. TOOLKIT: GO TOOLS 05_toolkit/code/tools.go
GO TOOLS & COMMANDS
go run main.go
go install
go build
go fmt main.go
go list
go vet
go doc fmt.Println
go get golang.org/x/lint/golint
golint
05. TOOLKIT: PACKAGES 05_toolkit/packages.md
package main
import (
PACKAGES
"fmt"
"math"
"reflect"
)
05. TOOLKIT: PACKAGES 05_toolkit/code/packages.go
PACKAGES
05_TOOLKIT/CODE/PACKAGES.GO
‣ Go packages
‣ Package visibility
‣ Custom packages
05. TOOLKIT: UNIT TESTING
UNIT TESTING
(JUST A CASUAL GLANCE)
05. TOOLKIT: UNIT TESTING 05_toolkit/testing.md
UNIT TESTING
average.go
average_test.go
go test
05. TOOLKIT: UNIT TESTING 05_testing/exercise_5a.md
(5 MINUTES)
EXERCISE #5A
TEST THE ADD METHOD
06. STRUCTS
06. WHAT DEFINES YOU?
STRUCTS
05. STRUCTS: DEFINING 06_structs/structs.md
STRUCTS
06_structs/code/structs.go
06 STRUCTS: EXERCISE 6A 06_structs/exercise_6a.md
(5 MINUTES)
EXERCISE #6A
WORK WITH STRUCTS
07. POINTERS
07. LET ME CHANGE YOU
POINTERS & REFERENCES
07. POINTERS
POINTERS
07. POINTERS 07_pointers/pointers.md
POINTERS *
A pointer in Go is a variable that holds the memory location of that
variable instead of a copy of its value.
07. POINTERS 07_pointers/pointers.md
POINTERS
Modifying Pointers
07_POINTERS/POINTERS.GO
> _TRY IT_
> Set both `name` and `namePointer` to string values.
> What happens?
> What does the error message mean?
07. POINTERS 07_pointers/pointers.md
POINTERS: SUMMARY
‣ Pointer type definitions are indicated with a * next to the type name
‣ Indicate that the variable will point to a memory location.
var namePointer *string
‣ Pointer variable values are visible with a * next to the variable name
var nameValue = *namePointer
‣ To read through a variable to see the pointer address
use a & next to the pointer variable name
var nameAddress = &namePointer
07. POINTERS 07_pointers/pointers.md
POINTERS
07_POINTERS/POINTERS.GO
‣ Pass by value
‣ Pointers & functions
‣ Pointers & structs
07. EXERCISE 7A: POINTERS 07_pointers/exercise_7a.md
(5 MINUTES)
EXERCISE #7A
PRACTICE POINTERS
08. YOU F***** UP
ERROR HANDLING
08. ERROR HANDLING 08_errors/errors.md
ERROR HANDLING
ERROR
- indicates that something bad happened, but it might be possible to
continue running the program.
- ie: A function that intentionally returns an error if something goes
wrong
PANIC
- happens at run time
- something happened that was fatal to your program and program
stops execution
- ex: Trying to open a file that doesn’t exist
08. ERROR HANDLING 08_errors/errors.md
type error interface {
Error() string
}
err := someFuncThatReturnsAnError()
ERROR
fmt.Println(err.Error())
08_ERRORS/CODE/ERRORS.GO
08. ERROR HANDLING 08_errors/errors.md
PANIC & DEFER
f, err := os.Open(filename)
defer f.Close()
panic(err.Error()) 08_ERRORS/CODE/ERRORS.GO
08. ERROR HANDLING
08_ERRORS/CODE/ERRORS.GO
RECOVER
‣ Panic is called during a run time error and fatally kill the program
‣ Recover tells Go what to do when that happens
‣ Returns what was passed to panic.
‣ Recover must be paired with defer, which will fire even after a panic
09. METHODS
STATEFUL FUNCTIONS
08. METHODS 09_methods/methods.md
METHODS 09_METHODS.CODE/METHODS.GO
*
09. METHODS: EXERCISE 9A 09_methods/exercise_9a.md
(5 MINUTES)
EXERCISE #9A
PRACTICE METHODS
10. INTERFACES
A SET OF BEHAVIORS THAT DEFINE A TYPE
10. INTERFACES 10_interfaces/interfaces.md
INTERFACES type Worrier interface {
CallFrequently([]Kid)
type Mom struct { CheckIfOvenIsOff()
FirstName: string
LastName: string }
Kids: []Kid
BookClubFriends: []Friend
} func (d Dad) CallFrequently(kids []Kid) {
fmt.Println(“Clean your room”)
type Dad struct {
FirstName: string }
LastName: string
func (m Mom) CallFrequently(kids []Kid)
Kids: []Kid
GolfFriends: []Friend fmt.Println(“Did you take your vitamins”)
} }
func (d Dad) CheckIfOvenIsOff() bool {}
func (m Mom) CheckIfOvenIsOff() bool {}
var susan = Mom{…} susan is both type Mom and type Worrier
var bob = Dad{…} bob is both type Dad and type Worrier
"If it walks like a duck, swims like a duck and quacks like a duck, then it’s a duck.”
10. INTERFACES 10_interfaces/interfaces.md
INTERFACES Interfaces describe the kind of behavior our types can execute.
10_INTERFACES/CODE/INTERFACES.GO
10. INTERFACES 10_interfaces/interfaces.md
THE EMPTY INTERFACE interface{}
‣ Specifies zero methods
‣ An empty interface may hold values of any type
‣ These can be used by code that expects an unknown type
‣ Allows you to call methods and functions on types when you aren’t
entirely sure what will be expected
‣ Think the any type in Typescript
10. INTERFACES 10_interfaces/interfaces.md
THE EMPTY INTERFACE interface{}
type User struct {} var people map[string]interface{}
type Admin struct {} people = map[string]interface{
“user”: User,
type Parent struct{} “admin”: Admin,
“parent”: Parent,
}
11. WEB SERVERS
BUILDING A TODO LIST
11. WEB SERVER: ROUTES 11_server/server.md
“net/http”
func main() {
ROUTES }
http.HandleFunc("/", home)
11_ROUTES/CODE/ROUTES.GO
11. WEB SERVER 11_server/code/server.go
(20 MINUTES)
EXERCISE #11A
BROWSER TODO LIST
A CODE-ALONG
12. FETCHING DATA
EXTERNAL API
12. API: EXERCISE 12 swapi.dev
(20 MINUTES)
EXERCISE #12
API ADVENTURES IN A GALAXY FAR FAR AWAY
A CODE-ALONG
13. CONCURRENCY 13_concurrency/concurrency.md
13. MULTITASKING
CONCURRENCY
13. CONCURRENCY 13_concurrency/concurrency.md
GOROUTINES
▸ A Goroutine is a lightweight thread managed by the Go runtime
▸ Implemented by adding the go keyword before executing a function
‣ Tells go to spin up a new thread to do that thing
13. CONCURRENCY: EXERCISE 13 13_concurrency/code/concurrency.go
(10 MINUTES)
EXERCISE #13
ADDING CONCURRENCY TO AN APP
A CODE-ALONG
14. FUTURE OF GO: ERRORS
ERROR WRAPPING
An error “e” can wrap another error “w" by providing an
Unwrap method that returns w. Both e and w are available to
programs, allowing e to provide additional context to w or to
reinterpret it while still allowing programs to make decisions
based on w.
14. WE SHOULD DO
THIS AGAIN SOMETIME
CONCLUSION
14. CONCLUSION: RESOURCES
RESOURCES
‣ - [Offical Golang Docs]
‣ (https://golang.org/doc/)
‣ - [How To Use Interfaces In Go]
‣ (https://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go)
‣ - [Introducing Go]
‣ (http://shop.oreilly.com/product/0636920046516.do), Caleb Doxsey, O'Reilly
Publications
‣ - [Web Applications With Go]
‣ (https://blog.scottlogic.com/2017/02/28/building-a-web-app-with-go.html)
‣ - [Go Language Programming Practical Basic Tutorial]
‣ (https://www.youtube.com/playlist?list=PLQVvvaa0QuDeF3hP0wQoSxpkqgRcgxMqX)
‣ - [Star Wars API]
‣ (https://swapi.co/)
‣ - My colleague Justin Holmes, and former colleagues Mike McCrary and Steven Bogacz
for their patience with my endless questions.
CONCLUSION: CONTACT ME
CONTACT ME
▸ Github: github.com/martensonbj
▸ Twitter: @martenson_bj
▸ Work: brenna.martenson@highwing.io
▸ LinkedIn: linkedin/martensonbj