Learn Golang in ~30 Minutes

I’ve been working with a student of mine recently in Golang and noticed that my skills were sort of lacking! So here’s a quick little cheat sheet reference for coding in Golang. If you need any help getting your computer setup to run Golang, check out Learn Go in 12 Minutes on YouTube.

If you haven’t already installed Golang and set up your environment, do that first…

Step 1: Install Golang

Then, create your “go” directory where you will store all of your golang projects on your local machine:

$ cd $HOME

$ mkdir go

$ cd go

$ mkdir src

$ cd src

Next, create a subdirectory for your project:

$ mkdir hello

$ cd hello

Now create a file called hello.go which will contain our hello, world program:

package main

import "fmt"

func main() {
	fmt.Printf("hello, golang\n")
}

Compile & Run:

$ go build

$ ./hello

Last, check out the example below (based on Learn Golang in 12 Minutes) as a reference/cheatsheet:

// REFERENCE (Learn Golang in 12 Minutes): https://www.youtube.com/watch?v=C8LgvuEBraI
package main
import (
"fmt"
)
func main() {
// functions
fmt.Println("hello, golang!")
// variables
var x int = 4
y := 7 // use walrus tooth operator to infer type
// if statements
if (x == 5) {
fmt.Println("x equals five!")
} else if (x != 5 && y == 7) {
fmt.Println("x does not equal five, but y equals seven...")
} else {
fmt.Println("I dunno man?")
}
// arrays (fixed length)
var a [5]int
a[0] = 100
a[1] = 101
a[2] = 102
a[3] = 103
a[4] = 104
fmt.Println(a[0])
// slices (adjustable length "array")
var b []int
b = append(b, 200)
b = append(b, 201)
b = append(b, 202)
b = append(b, 203)
b = append(b, 204)
fmt.Println(b[0])
// maps (key value pairs, "dictionary")
c := make(map[string]int)
c["foo"] = 300
c["bar"] = 301
c["baz"] = 302
fmt.Println(c["foo"])
// loops
// (no while loops in golang, only for loops!)
for i:= 0; i < 5; i++ {
fmt.Println(i)
}
// if you need something like a while loop,
// this can be accomplished with a for loop
// like so...
j := 0
for j < 1 {
fmt.Println("look at me go!")
fmt.Println("just kidding... lets shut it down!")
j = 1
}
}
view raw learngo.go hosted with ❤ by GitHub

Need to work with command line user input? Another cheatsheet:

// Command Line User Input in Golang
// REFERENCE: https://stackoverflow.com/questions/20895552/how-to-read-from-standard-input-in-the-console
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print(">>> ")
userInput, _ := reader.ReadString('\n')
fmt.Println(userInput)
fmt.Print(">>> ")
userInput2, _ := reader.ReadString('\n')
fmt.Println(userInput2)
fmt.Print(">>> ")
userInput3, _ := reader.ReadString('\n')
fmt.Println(userInput3)
}
view raw userinput.go hosted with ❤ by GitHub

Need to ping a JSON API? More cheatsheet goodness from the folks at RapidAPI:

package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "https://community-hacker-news-v1.p.rapidapi.com/item/8863.json?print=pretty"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("x-rapidapi-host", "community-hacker-news-v1.p.rapidapi.com")
req.Header.Add("x-rapidapi-key", "472e13f6d7msh84492a2444096d4p1edbffjsn3ff4c1075778")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}

What about functions? See below:

package main
import(
"fmt"
)
func main() {
var favoriteNumbers []float64
favoriteNumbers = append(favoriteNumbers, 13.0)
favoriteNumbers = append(favoriteNumbers, 27.0)
favoriteNumbers = append(favoriteNumbers, 56.0)
favoriteNumbers = append(favoriteNumbers, 3.0)
favoriteNumbers = append(favoriteNumbers, 99.0)
favoriteNumbers = append(favoriteNumbers, 15.0)
averageFavoriteNumber := average(favoriteNumbers)
// REFERENCE (String Formatting): https://gobyexample.com/string-formatting
fmt.Printf("Average Favorite Number: %v", averageFavoriteNumber)
}
func average(numbers []float64) float64 {
var sum float64 = 0
for i := 0; i < len(numbers); i++ {
sum += numbers[i]
}
mean := sum / float64(len(numbers))
return mean
}
view raw funkyfunc.go hosted with ❤ by GitHub

Structs…

package main
import(
"fmt"
)
func main() {
fmt.Println("It's time to learn about Structs...")
chris := Person{FirstName: "Christopher", LastName: "Pedersen", Age: 33, Height: 68, Sex: "male"}
fmt.Println("Our first struct is a Person")
fmt.Printf("Our Person's first name is: %s \n", chris.FirstName)
fmt.Printf("Last name is: %s \n", chris.LastName)
fmt.Printf("Age: %d \n", chris.Age)
fmt.Printf("Height (in inches): %d \n", chris.Height)
fmt.Printf("Sex: %s", chris.Sex)
}
type Person struct {
FirstName string
LastName string
Age int
Height int
Sex string
}
view raw mystruct.go hosted with ❤ by GitHub

Confused about the need for Interfaces? See this explanation by Andy Joiner on Stack Overflow: Why are interfaces needed in Golang?

 

topherPedersen