CodeCademy Go
CodeCademy Go
Introduction
Go, or golang is an open sourced programming language. The designers of Go aimed to
“eliminate the slowness and clumsiness of software development at Google, and thereby to make
the process more productive and scalable”. It has modern features like garbage collection and it
also takes advantage of multi-core computer capabilities with built-in concurrency support.
Go uses a compiler. To compile a program written in Go, we write:
go build program.go // replace “program.go” with your written program
./program // to execute the file
The go run command combines both the compilation and the execution of the code for us. It will
not create an executable file in our current folder.
go run program.go // will compile and execute program
Every go program starts with a package declaration, which informs the compiler whether to create
an executable or library. With a library being a collection of code that can be used in other
programs. Programs with the package declaration package main will create an executable file.
Go ignores whitespace, but it makes code easier to read. The import keyword allows us to bring in
and use code from other packages. Package names are enclosed in double quotes. Packages
group related code together, allow code to be reusable and make it easier to maintain. We only
import packages that are used.
Code 4/9:
package main
Functions exist in go, start with func and have curly braces.
A file that has a package main declaration will automatically run the main function.
Code 5/9:
package main
import "fmt"
We can use a single import with a pair of parentheses that contain our packages. We separate
each package on a different line. We can also provide an alias to a package by including the alias
name before the file, making it easier to refer to the package.
Code 6/9:
package main
import "fmt"
import t "time"
func main() {
fmt.Println("Hello World")
fmt.Println(t.Now())
}
Comment using // and /* */
Code 7/9:
package main
import "fmt"
func main() {
//Are we racing or coding?
/*
fmt.Println("Ready")
fmt.Println("Set")
*/
fmt.Println("Gooooo!")
}
import "fmt"
func main() {
fmt.Println("Using the 'go doc' command is helpful")
fmt.Println("You can find out more about a package")
fmt.Println("Or about a function inside the package")
fmt.Println("Try it out in the terminal!")
}
Gopher It
Code:
package main
func main() {
f.Println(" `.-::::::-.` ")
f.Println(".:-::::::::::::::-:.")
f.Println("`_::: :: :::_`")
f.Println(" .:( ^ :: ^ ):. ")
f.Println(" `::: (..) :::. ")
f.Println(" `:::::::UU:::::::` ")
f.Println(" .::::::::::::::::. ")
f.Println(" O::::::::::::::::O ")
f.Println(" -::::::::::::::::- ")
f.Println(" `::::::::::::::::` ")
f.Println(" .::::::::::::::. ")
f.Println(" oO:::::::Oo ")
f.Println(t.Now())
}
Variables and Types
Go has literals, an unnamed fixed value in source code. These can be written into code as it and
can have arithmetic operation performed on them.
Code 2/15:
package main
import "fmt"
func main() {
// Add a fmt.Println() statement
// that prints 2235 * 1231
fmt.Println(2235 * 1231)
}
There are also named values like constants and variables. Constants cannot be updated when the
program is running. Use the const keyword to create a Constant.
Code 3/15:
package main
import "fmt"
func main() {
// Create the constant earthsGravity
// here and set it to 9.80665
const earthsGravity = 9.80665
// Here's where we print out the gravity:
fmt.Println(earthsGravity)
}
Complex numbers are pairs of floating-point numbers where the second part of the pair is marked
with the “imaginary” unit i. They are useful when reasoning in 2-dimensional space and have other
utilizations that make them relevant for involved calculations. Examples include: 3i, 7+2i, -14 -.05i
Go has 15 different numeric types that fall into three categories: int, float and complex. This
includes 11 different integer types, 2 different floating-point types and 2 different complex number
types. Types also indicate how many bits will be used to represent the data. Integers can be
broken down into two categories: signed and unsigned. Unsigned integers can only be positive.
Booleans are either true or false. It only needs one bit to store a Boolean value.
A variable must be named and can change during the running of the program unlike a constant.
In go variables or constants that are exported at the package level (that is, identifiers that can be
used form a package other than the one where they are defined) must begin with a capital letter.
https://stackoverflow.com/questions/38616687/which-way-to-name-a-function-in-go-camelcase-or-
semi-camelcase
Code 6/15:
package main
func main() {
// Create the variable jellybeanCounter
// here and make its type int8
var jellybeanCounter int8 // shows error as not used
}
import "fmt"
func main() {
var jellybeanCounter int8
fmt.Println(jellybeanCounter)
}
Code 8/15:
package main
import "fmt"
func main() {
var numOfFlavors int
// Assign a value for numOfFlavors below:
numOfFlavors = 57
fmt.Println(numOfFlavors)
fmt.Println(flavorScale)
import "fmt"
func main() {
// Define a string variable
// called favoriteSnack
var favoriteSnack string
// Assign a value to
// favoriteSnack
favoriteSnack = "kladfjs"
import "fmt"
func main() {
// Create three variables
// emptyInt an int8
var emptyInt int8
// emptyFloat a float32
var emptyFloat float32
// and emptyString a string
var emptyString string
// Finally, print them all out
fmt.Println(emptyInt, emptyFloat, emptyString)
}
We can use the := operator to declare a variable without explicitly stating its type. We might use it
if we know what value we want our variable to store when creating it. Floats created in this way
are of type float64. Integers are either int32 or int64 depending on the size of the architecture.
We can use a separate syntax instead to declare a variable and infer its type:
var variableName = true
Code 11/15:
package main
import "fmt"
func main() {
// Define daysOnVacation using := below:
daysOnVacation := 5
import "fmt"
func main() {
// Define cupsOfCoffeeConsumed here
var cupsOfCoffeeConsumed int
// Give a value to cupsOfCoffeeConsumed
cupsOfCoffeeConsumed = 5123
// Print out cupsOfCoffeeConsumed
fmt.Println(cupsOfCoffeeConsumed)
}
Code 13/15:
package main
import "fmt"
func main() {
coolSneakers := 65.99
niceNecklace := 45.50
import "fmt"
func main () {
// Define magicNum and powerLevel below:
var magicNum, powerLevel int32
magicNum = 2048
powerLevel = 9001
fmt.Println("magicNum is:", magicNum, "powerLevel is:", powerLevel)
// Define amount and unit below:
amount, unit := 10, "doll hairs"
fmt.Println(amount, unit, ", that's expensive...")
}
Comic Mischief
Code:
package main
import "fmt"
func main(){
var publisher, writer, artist, title string
var year, pageNumber uint // unsigned as positive vars
var grade float32
title = "Mr. GoToSleep"
writer = "Tracey Hatchet"
artist = "Jewel Tampson"
publisher = "DizzyBooks Publishing Inc."
year = 1997
pageNumber = 14
grade = 6.5
fmt.Println(title, "written by", writer, "drawn by", artist,
"published by", publisher, "made in", year, "total pages", pageNumber,
"grade", grade)
title = "Epic Vol. 1"
writer = "Ryan N. Shawn"
artist = "Phoebe Paperclips"
year = 2013
pageNumber = 160
grade = 9.0
fmt.Println(title, "written by", writer, "drawn by", artist,
"published by", publisher, "made in", year, "total pages", pageNumber,
"grade", grade)
}
fmt Package
fmt is one of Go’s core packages. It has a broader purpose of helping us format data.
Print() prints data but with no newline at the end. Printf() can print formatted data.
Sprint(), Sprintln() and Sprintf() is used to format data but not print it.
Scan() can scan for input.
More: https://golang.org/pkg/fmt/
Println() prints it arguments with an included space between each argument.
Print() does not and also does not provide a line break after.
Code 2/8:
package main
import "fmt"
func main() {
fmt.Println("Let's first see how", "the Println() method works.")
fmt.Println("Notice that each statement adds a newline for us.")
fmt.Println("There's also a default space", "between the string
arguments.")
Using fmt.Printf() we can interpolate strings, leave placeholders in a string and use values to fill in
the placeholders. The %v is our place holder and is known as a verb in Go.
Code 3/8:
package main
import "fmt"
func main() {
animal1 := "cat"
animal2 := "dog"
import "fmt"
func main() {
floatExample := 1.75
// Edit the following Printf for the FIRST step
fmt.Printf("Working with a %T", floatExample)
yearsOfExp := 3
reqYearsExp := 15
// Edit the following Printf for the SECOND step
fmt.Printf("I have %d years of Go experience and this job is asking
for %d years.", yearsOfExp, reqYearsExp)
stockPrice := 3.50
// Edit the following Printf for the THIRD step
fmt.Printf("Each share of Gopher feed is $%.2f!", stockPrice)
}
Sprint() and Sprintln() format strings but don’t print them. They return a string instead.
Code 5/8:
package main
import "fmt"
func main() {
step1 := "Breathe in..."
step2 := "Breathe out..."
import "fmt"
func main() {
template := "I wish I had a %v."
pet := "puppy"
fmt.Println(wish)
}
fmt.Scan() allows us to get user input. fmt.Scan(&response) takes the first value before a space
and stores it in the var response. If we were expecting two values we would need to declare two
variables ahead of time. fmt.Scan() expects addresses for arguments, hence the & before.
Code 7/8:
package main
import "fmt"
func main() {
fmt.Println("What would you like for lunch?")
import "fmt"
func main() {
heistReady := false
if heistReady {
fmt.Println("Let's Go!")
}
}
if (true/false) {} else {}
Code 3/13:
package main
import "fmt"
func main() {
heistReady := false
if heistReady {
fmt.Println("Let's go!")
} else {
fmt.Println("Act normal.")
}
}
import "fmt"
func main() {
lockCombo := "2-35-19"
robAttempt := "1-1-1"
import "fmt"
func main() {
vaultAmt := 2356468
import "fmt"
func main() {
rightTime := true
rightPlace := true
enoughRobbers := false
enoughBags := true
import "fmt"
func main() {
readyToGo := true
if !readyToGo {
fmt.Println("Start the car!")
} else {
fmt.Println("What are we waiting for??")
}
}
if () {} else if () {} else {}
Code 8/13:
package main
import "fmt"
func main() {
amountStolen := 64650
import "fmt"
func main() {
name := "H. J. Simp"
import "fmt"
func main() {
if success := true; success {
fmt.Println("We're rich!")
} else {
fmt.Println("Where did we go wrong?")
}
amountStolen := 50000
import (
"fmt"
"math/rand"
)
func main() {
// Edit amountLeft below:
amountLeft := rand.Intn(10000)
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Add your code below:
rand.Seed(time.Now().UnixNano())
amountLeft := rand.Intn(10000)
Bank Heist
Code:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
isHeistOn := true
eludedGuards := rand.Intn(100) // 0-99
if (eludedGuards >= 50) {
fmt.Println("Looks like you've managed to make it past the guards.
Good job, but remember, this is the first step.")
} else {
isHeistOn = false
fmt.Println("Plan a better disguise next time?")
}
openedVault := rand.Intn(100)
if (isHeistOn && openedVault >= 70) {
fmt.Println("Grab and GO!")
} else if (isHeistOn) {
isHeistOn = false
fmt.Println("Vault cannot be opened")
}
leftSafely := rand.Intn(5) // 0-4
if (isHeistOn) {
switch (leftSafely){
case 0:
isHeistOn = false
fmt.Println("Failed heist")
case 1:
isHeistOn = false
fmt.Println("Failed heist")
case 2:
isHeistOn = false
fmt.Println("Failed heist")
case 3:
isHeistOn = false
fmt.Println("Failed heist")
default:
fmt.Println("Start the getaway car!")
}
if isHeistOn {
amtStolen := 10000 + rand.Intn(1000000)
fmt.Printf("Amount taken: %d \n", amtStolen)
}
}
Functions
A function is a block of code designed to be reused
Code 2/9:
package main
import "fmt"
func main() {
// Call your function here:
eatTacos()
}
Scope is a concept that refers to where the values and functions are defined and where they can
be accessed. You can only refer to variables or functions defined within a specific namespace.
Code 3/9:
package main
import "fmt"
func startGame() {
instructions := "Press enter to start..."
fmt.Println(instructions)
}
func main() {
startGame()
}
A function can be given a return type. It needs a return statement to pass back a value and stop
the function from executing any more code.
Code 4/9:
package main
import (
"fmt"
"time"
)
func main() {
var nyLate string
nyLate = isItLateInNewYork()
fmt.Println(nyLate)
}
Use parameters to provide functions with information. If all parameters have the same type we can
only write the type once at the end.
Code 5/9:
package main
import "fmt"
func main() {
myAge := 25
Code 6/9:
package main
import (
"math"
"fmt"
)
func main() {
var a, b, c, d float64
a = .0214
b = 1.02
c = 0.312
d = 4.001
fmt.Println(a, b, c, d)
}
func main() {
var likes, shares int
if likes > 5 {
fmt.Println("Woohoo! We got some likes.")
}
if shares > 10 {
fmt.Println("We went viral!")
}
}
defer tells go to run a function but at the end of the current function, this is useful for logging, file
writing and other utilities.
Code 8/9:
package main
import "fmt"
func queryDatabase(query string) string {
defer disconnectDatabase()
var result string
connectDatabase()
// Add deferred call to disconnectDatabase() here
func connectDatabase() {
fmt.Println("Connecting to the database.")
}
func disconnectDatabase() {
fmt.Println("Disconnecting from the database.")
}
func main() {
queryDatabase("SELECT * FROM coolTable;")
}
Interstellar Travel
Code:
package main
import "fmt"
func main() {
// Test your functions!
import "fmt"
func main() {
treasure := "The friends we make along the way."
Pointers are variables that specifically store addresses. The * operator signifies that a variable will
store an address. We can also declare a pointer implicitly like other variables using :=.
Code 3/6:
package main
import "fmt"
func main() {
star := "Polaris"
Dereferencing (or indirecting) is using a pointer to access the address and change its value.
We need to use the * operator on a pointer and then assign a new value.
Code 4/6:
package main
import "fmt"
func main() {
star := "Polaris"
starAddress := &star
We can make functions using pointers and dereferencing to change variables in another scope
Code 5/6:
package main
import "fmt"
func main() {
greeting := "Hello there!"
Code 1/10: