← Back to Blog

Go Programming Notes

Go Golang Programming

Syntax & Overview

  • Statically typed
  • Compiled (go run file_name.go), simpler than C++'s g++ filename.cpp -> ./a.out
  • Packages similar to Python modules but different syntax
  • No semicolons necessary (unlike C/C++), but curly braces used
  • Functions start with func, arguments must include type, output type must also be specified

General Structure

packages
imports
func(arg type) output_type {
  function details
}

Example Function

package main
import "fmt"

func add_567(num int) int {
  var sum int
  i := 567
  sum = num + i
  return sum
}

func main() {
  fmt.Println(add_567(5))
}

Loops in Go

No defined keyword for while loops, instead use for loop:

package main
import (
    "fmt"
    "math/rand"
)

func generate_random() int {
    fmt.Println("Generating random number...")
    num := rand.Intn(100)
    fmt.Println(num)
    return num
}

func try() int {
    var inp int
    fmt.Println("Guess a number between 1 and 100:")
    fmt.Scan(&inp)
    return inp
}

func main() {
    var randm int = generate_random()
    var guess int
    guess = try()
    for tries := 4; tries > 0; tries-- {
        // game logic
    }
}

Infinite Loops

for {
  function
}

Maps and Iteration

Like Python, JS, and many other languages, Go contains useful iterative tools like map, range, continue, break, etc.

Accessing items in an array using the map function:

package main
import "fmt"

func main() {

    resistors := map[int]string{
        200: "0805",
        150: "0605",
    }

    for index, value := range resistors {
        fmt.Println("Resistance: ", index, "Size: ", value)
    }

}

Learning the implementation of the map function in Go improved understanding and encouraged more frequent use in Python as well.