Go time
Taking notes while learning some Go
Go concepts #
Every Go file is part of a package.
Packages contain a collection of Go files.
Modules contain a collection of packages.
Initialize a project #
go mod init [pj name or github address]
Main #
main is a special package that tells the compiler where your program begins
package main
main package requires a main function:
package main
func main(){
}
import packages with 'import'
use 'fmt' package to print stuff to the screen
package main
import "fmt"
func main(){
fmt.Println("Hi friend!")
}
build the program with go build:
go build whatever.go
run the program with go run:
go run whatever.go
Hi friend!
daaaaaaang, im ready for devops
Variables #
Variable type must be declared
var var-name type
package main
import "fmt"
func main(){
var intNum int64
fmt.Println(intNum)
}
int types #
int8, int16, int32, int64 -- default 32/64 depending on arch
unsigned ints for positive numbers only, lower memory cost:
uint
float #
float32, float64, must specify
booleans #
bool, true or false
Combining variables #
Variables must be same type to perform functions on them
Can use comma, +, -, etc.
package main
import "fmt"
func main(){
fmt.Println("Hi again, old friend!")
var awkward string = "I can't remember your name..."
name := "Old Friend"
fmt.Println(name + ",", awkward)
}
❯ ./hi-friend
Hi again, old friend!
Old Friend, I can't remember your name...
Functions #
Functions follow the style func func-name(parameters) return-type { }
the return type must be declared, in this case we return a string:
func hello_name(name string) string {
return "Howdy, " + name
}
Functions can be combined on one line:
func language(tongue string) string {
return "I don't know any " + tongue
}
func hello_name(name string) string {
return "Howdy, " + name + " -- "
}
func main(){
name := "Skeeter"
tongue := "Python"
fmt.Println(hello_name(name), language(tongue))
}
❯ go run language.go
Howdy, Skeeter -- I don't know any Python
Arrays #
Arrays are fixed size, cannot change
var array1 [# of items]type = [# of items]type{item1, item2, item3}
var array1 [5]int = [5]int{42, 52, 62, 72, 82}
Slices #
like arrays, but no need to define the size. Can grow and shrink. use append function to grow
slice1 := []int{42, 52, 62, 72, 82}
Loops #
func main(){
week := []string{"thursday", "friday", "saturday", "sunday", "monday", "tuesday", "wednesday"}
for index, day := range week {
fmt.Println(index, day)
}
Maps #
like a dictionary, with key:value.
make(map[key-type]value-type)
manipulating items in a map:
func main() {
phoneBook := make(map[string]string)
// add stuff to map
phoneBook["Brian"] = "111-1111"
phoneBook["Skeeter"] = "111-2222"
phoneBook["Jalapeno"] = "111-3333"
phoneBook["Poblano"] = "111-4444"
// print current book
for name, number := range phoneBook {
fmt.Println(name, "--", number)
}
// change Skeeter's number
phoneBook["Skeeter"] = "222-1111"
// warn the user
fmt.Println("...\nA number changed!\n...\nHere's the new phonebook:")
for name, number := range phoneBook {
fmt.Println(name, "--", number)
}
// delete Poblano's number
delete(phoneBook, "Poblano")
// deliver a eulogy
fmt.Println("...\nPoblano is no longer with us...\n...\nRIP, Poblano.\n...\nHere's the new phonebook:")
for name, number := range phoneBook {
fmt.Println(name, "--", number)
}
}
User inputs, nested if/elif #
fmt.Scanln(desiredinput)
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// ask questions
var numguesses int
var numrange int
fmt.Println("Welcome to the guessing game!\n...\nGuess my number and win the prize!\n...\nHow many guesses would you like? (1-99)")
fmt.Scanln(&numguesses)
fmt.Println(numguesses, " guesses, you got it.\n...\nNow choose the range! Between 1 and __ (max 100):")
fmt.Scanln(&numrange)
// plant seeds
rand.Seed(time.Now().UnixNano())
// sprout seed
randnum := rand.Intn(numrange) + 1
var guess int
attempts := numguesses
// start game
fmt.Println("Guess a number between 1 and ", numrange)
for i := 0; i < attempts; i++ {
fmt.Print("Enter your guess: ")
fmt.Scanln(&guess)
// give hints
// calculate difference
difference := guess - randnum
// if negative, make positive
if difference < 0 {
difference = -difference
}
if guess < randnum {
if difference > numrange/5 {
fmt.Println("Way too low!")
} else {
fmt.Println("Too low!")
}
} else if guess > randnum {
if difference > numrange/5 {
fmt.Println("Way too high!")
} else {
fmt.Println("Too high!")
}
} else {
fmt.Println("You got it! The number was ", randnum)
return
}
}
fmt.Println("Out of guesses! Better luck next time. The number was ", randnum)
}
simple math / if-else practice #
package main
import "fmt"
func main () {
// get current age
fmt.Println("Hey! how old are you?")
var age int
fmt.Scanln(&age)
// calculate # of years until you can do stuff
// if negative, make positive
fmt.Println("Cool!", age, "years old. Let's see your milestones:")
fmt.Println("...")
var yearstoadult int
yearstoadult = 18 - age
if yearstoadult > 0 {
fmt.Println("You will be an adult in", yearstoadult, "years.")
} else {
if yearstoadult < 0 {
yearstoadult = -yearstoadult
fmt.Println("You became an adult", yearstoadult, "years ago.")
} else {
if yearstoadult == 0 {
fmt.Println("You became an adult this year!")
}
}
}
fmt.Println("...")
var yearstodrink int
yearstodrink = 21 - age
if yearstodrink > 0 {
fmt.Println("You can buy alcoholic beverages in", yearstodrink, "years.")
} else {
if yearstodrink < 0 {
yearstodrink = -yearstodrink
fmt.Println("You were able to buy alcoholic beverages", yearstodrink, "years ago.")
} else {
if yearstodrink == 0 {
fmt.Println("You can buy alcoholic beverages this year!")
}
}
}
fmt.Println("...")
var yearstocar int
yearstocar = 25 - age
if yearstocar > 0 {
fmt.Println("You can rent a car in", yearstocar, "years.")
} else {
if yearstocar < 0 {
yearstocar = -yearstocar
fmt.Println("You were able to rent a car", yearstocar, "years ago.")
} else {
if yearstocar == 0 {
fmt.Println("You can rent a car this year!")
}
}
}
fmt.Println("...")
var yearstoretire int
yearstoretire = 67 - age
if yearstoretire > 0 {
fmt.Println("You can retire in", yearstoretire, "years.")
} else {
if yearstoretire < 0 {
yearstoretire = -yearstoretire
fmt.Println("You could have retired", yearstoretire, "years ago.")
} else {
if yearstoretire == 0 {
fmt.Println("You can retire this year!")
}
}
}
}
chat jippity said I should clean that up a bit and not repeat myself. Let's try:
package main
import "fmt"
//calculate age until milestones
func ageCalc(age, milestoneAge int, milestoneName string) {
years := milestoneAge - age
if years > 0 {
fmt.Printf("%s in %d years.\n", milestoneName, years)
} else if years < 0 {
fmt.Printf("%s %d years ago\n", milestoneName, -years)
} else {
fmt.Printf("%s this year!\n", milestoneName)
}
}
func main() {
//ask for age
fmt.Println("Hey! How old are you?")
var age int
fmt.Scanln(&age)
fmt.Println("Cool!", age, "years old. Let's see your milestones:")
fmt.Println("...")
//use ageCalc function to print results
ageCalc(age, 18, "Reach adulthood --")
ageCalc(age, 21, "Buy alcoholic beverages --")
ageCalc(age, 25, "Rent a car --")
ageCalc(age, 67, "Retirement age --")
fmt.Println("...")
}
From 74 lines to 29 lines. Not bad
compile for windows #
GOOS=windows GOARCH=amd64 go build -o age-calc-v2.exe age-calc-v2.go
- Previous: ZFS on Thinkpad: Automated Snapshots
- Next: OpenVPN inside LXC container