umma.dev

Learning Go

Go code snippets from a past course.

Address and Pointers

Addresses

package main

import "fmt"

func main() {
	treasure := "The friends we make along the way."

	fmt.Println(&treasure)
}

Dereferencing

package main

import "fmt"

func main() {
	star := "Polaris"

	starAddress := &star

	*starAddress = "Sirius"

	fmt.Println("The actual value of star is", star)
}

Pointers

package main

import "fmt"

func main() {
	star := "Polaris"

	starAddress := &star

	fmt.Println("The address of star is", starAddress)
}

Values (Difference Scope)

package main

import "fmt"

func brainwash(saying *string) {
	*saying = "Beep Boop."
}

func main() {
	greeting := "Hello there!"
	brainwash(&greeting)
	fmt.Println("greeting is now:", greeting)
}

Conditionals

package main

import "fmt"

func main() {
	rightTime := true
	rightPlace := true

	if rightTime && rightPlace {
		fmt.Println("We're outta here!")
	} else {
		fmt.Println("Be patient...")
	}


	enoughRobbers := false
	enoughBags := true

	if enoughRobbers || enoughBags{
		fmt.Println("Grab everything!")
	} else {
		fmt.Println("Grab whatever you can!")
	}
}
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())

	isHeistOn:=true
	eludedGuards:=rand.Intn(100)

	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)
	fmt.Println(isHeistOn)

	if isHeistOn && openedVault >=70 {
		fmt.Println("Grab and GO!")
	} else if isHeistOn {
		fmt.Println("Vault can't be opened.")
	} else {
		fmt.Println("what's the combo to this lock again??")
	}

	leftSafely:=rand.Intn(5)
	if isHeistOn {
		switch leftSafely {
		case 0:
			isHeistOn = false
			fmt.Println("Looks like you tripped an alarm... run?")
		case 1:
			fmt.Print("Turns out the vault doors don't open from the inside...")
		case 2 :
			fmt.Print("What an earth is happening?")
		case 3:
			fmt.Print("ugh...?")
		default:
			fmt.Print("Start the getaway car!")
		}
		amtStole:= 1000+rand.Intn(1000000)
		fmt.Print(amtStole)

	}
}
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	amountLeft := rand.Intn(10000)

	fmt.Println("amountLeft is: ", amountLeft)

		if amountLeft > 5000 {
			fmt.Println("What should I spend this on?")
	} else {
		fmt.Println("Where did all my money go?")
	}
}
package main

import "fmt"

func main() {
	if success := true; success {
			fmt.Println("We're rich!")
		} else {
			fmt.Println("Where did we go wrong?")
		}

		amountStolen := 50000

	switch numOfThieves := 5; numOfThieves {
		case 1:
			fmt.Println("I'll take all $", amountStolen)
		case 2:
		fmt.Println("Everyone gets $", amountStolen/2)
		case 3:
			fmt.Println("Everyone gets $", amountStolen/3)
		case 4:
		fmt.Println("Everyone gets $", amountStolen/4)
		case 5:
			fmt.Println("Everyone gets $", amountStolen/5)
		default:
			fmt.Println("There's not enough to go around...")
		}
	}
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())

	amountLeft := rand.Intn(10000)

	fmt.Println("amountLeft is: ", amountLeft)

		if amountLeft > 5000 {
			fmt.Println("What should I spend this on?")
	} else {
		fmt.Println("Where did all my money go?")
	}
}
package main

import "fmt"

func main() {
	name := "H. J. Simp"

	switch name {
	case "butch":
		fmt.Println("Head to Robbers Roost.")
	case "bonnie":
			fmt.Println("Stay put in Joplin.")
	default:
		fmt.Println("Just hide!")
	}
}

Functions

package main
import "fmt"

func queryDatabase(query string) string {
	var result string
	connectDatabase()
	defer disconnectDatabase()
	if query == "SELECT * FROM coolTable;" {
		result = "NAME|DOB\nVincent Van Gogh|March 30, 1853"
	}
	fmt.Println(result)
	return result
}

func connectDatabase() {
	fmt.Println("Connecting to the database.")
}

func disconnectDatabase() {
	fmt.Println("Disconnecting from the database.")
}

func main() {
	queryDatabase("SELECT * FROM coolTable;")
}
package main

import "fmt"

func fuelGauge(fuel int) {
	fmt.Printf("%d left", fuel)
}

func calculateFuel(planet string) (int) {
	var fuel int
	if planet == "Mercury" {
		fuel = 500000
	} else if planet == "Venus" {
		fuel = 300000
	} else if planet == "Mars" {
		fuel = 700000
	}
	return fuel
}

func greetPlanet (planet string) {
	fmt.Print("Welcome to planet ", planet)
}

func cantFly() {
	fmt.Print("We do not have the available fuel to fly there.")
}

func flyToPlanet(planet string, fuel int) (int){
	var fuelRemaining, fuelCost int
	fuelRemaining = fuel
	fuelCost = calculateFuel(planet)
	if fuelRemaining >= fuelCost {
		greetPlanet(planet)
		fuelRemaining -= fuelCost
	} else {
		cantFly()
	}
	return fuelRemaining
}

func main() {
	fuel := 1000000
	planetChoice := "Venus"

	fuel = flyToPlanet(planetChoice, fuel)
	fuelGauge(fuel)
}
package main
import "fmt"

func getLikesAndShares(postId int) (int, int) {
	var likesForPost, sharesForPost int
	switch postId {
	case 1:
		likesForPost = 5
		sharesForPost = 7
	case 2:
		likesForPost = 3
		sharesForPost = 11
	case 3:
		likesForPost = 22
		sharesForPost = 1
	case 4:
		likesForPost = 7
		sharesForPost = 9
	}
	fmt.Println("Likes: ", likesForPost, "Shares: ", sharesForPost)
	return likesForPost, sharesForPost
}

func main() {
	var likes, shares int

	likes, shares = getLikesAndShares(4)

	if likes > 5 {
		fmt.Println("Woohoo! We got some likes.")
	}
	if shares > 10 {
		fmt.Println("We went viral!")
	}
}
package main
import "fmt"

func computeMarsYears(earthYears int) int {
	earthDays := earthYears * 365
	marsYears := earthDays / 687
	return marsYears
}

func main() {
	myAge := 25

	myMartianAge := computeMarsYears(myAge)
	fmt.Println(myMartianAge)
}
package main
import (
	"fmt"
	"time"
)

func isItLateInNewYork() string {
	var lateMessage string
	t := time.Now()
	tz, _ := time.LoadLocation("America/New_York")
	nyHour := t.In(tz).Hour()
	if nyHour < 5 {
		lateMessage = "Goodness it is late"
	} else if nyHour < 16 {
		lateMessage = "It's not late at all!"
	} else if nyHour < 19 {
		lateMessage = "I guess it's getting kind of late"
	} else {
		lateMessage = "It's late"
	}
	return lateMessage
}

func main() {
	var nyLate string
	nyLate = isItLateInNewYork()
	fmt.Println(nyLate)
}
package main
import (
	"math"
	"fmt"
)

func specialComputation(x float64) float64{
	return math.Log2(math.Sqrt(math.Tan(x)))
}
func main() {
	var a, b, c, d float64
	a = .0214
	b = 1.02
	c = 0.312
	d = 4.001

	a = specialComputation(a)
	b = specialComputation(b)
	c = specialComputation(c)
	d = specialComputation(d)

	fmt.Println(a, b, c, d)
}
package main

import "fmt"

func startGame() {
	instructions := "Press enter to start..."
	fmt.Println(instructions)
}

func main() {
	startGame()
}

Variables and Types

package main

import "fmt"

func main() {
	const earthsGravity = 9.80665
	fmt.Println(earthsGravity)
}
package main

import "fmt"

func main() {
	daysOnVacation:= 5
	var hoursInDay = 24
	fmt.Println("You have spent", daysOnVacation * hoursInDay, "hours on vacation.")
}
package main

import "fmt"

func main () {
	var magicNum, powerLevel int32
	magicNum = 2048
	powerLevel = 9001
	fmt.Println("magicNum is:", magicNum, "powerLevel is:", powerLevel)

	amount, unit := 10, "doll hairs"
	fmt.Println(amount, unit, ", that's expensive...")
}
package main

import "fmt"

func main() {
	animal1 := "cat"
	animal2 := "dog"

	fmt.Printf("Are you a %v or a %v person?", animal1, animal2)
}
package main

import "fmt"

func main() {
	var publisher, writer, artist, title string
	var year, pageNumber int
	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, "publisher", publisher, "in", year, "with", pageNumber, "pages", grade)

	title="Epic Vol. 1"
	writer = "Ryan N. Shawn"
	artist = "Phoebe Paperclips"
	year = 2013
	pageNumber = 160
	grade = 9

	fmt.Println(title, "written by", writer, "drawn by", artist, "publisher", publisher, "in", year, "with", pageNumber, "pages", grade)
}
package main

import "fmt"

func main() {
	step1 := "Breathe in..."
	step2 := "Breathe out..."

	meditation := fmt.Sprintln(step1, step2)
	fmt.Print(meditation)
}
package main

import "fmt"

func main() {
	template := "I wish I had a %v."
	pet := "puppy"

	var wish string

	wish = fmt.Sprintf(template, pet)

	fmt.Println(wish)
}
package main

import "fmt"

func main() {
	coolSneakers := 65.99
	niceNecklace := 45.50
	var taxCalculation float64
	taxCalculation += coolSneakers
	taxCalculation += niceNecklace
	taxCalculation *= 0.08875
	fmt.Println("Purchase of", coolSneakers + niceNecklace, "with 8.875% sales tax", taxCalculation, "equal to", coolSneakers + niceNecklace + taxCalculation)
}
package main

import "fmt"

func main() {
	var emptyInt int8
	var emptyFloat float32
	var emptyString string

	fmt.Println(emptyInt, emptyFloat, emptyString)
}
package main

import "fmt"

func main() {
	fmt.Println("What would you like for lunch?")

	var food string
	fmt.Scan(&food)

	fmt.Printf("Sure, we can have %v for lunch.", food)
}

//go run main.go
package main

import "fmt"

func main() {
	floatExample := 1.75
	fmt.Printf("Working with a %T", floatExample)

	fmt.Println("\n***")

	yearsOfExp := 3
	reqYearsExp := 15
	fmt.Printf("I have %d years of Go experience and this job is asking for %d years.", yearsOfExp, reqYearsExp)

	fmt.Println("\n***")

	stockPrice := 3.50
	fmt.Printf("Each share of Gopher feed is $%.2f.", stockPrice)
}