Go (Golang)
Go (Golang) is a statically-typed, compiled programming language by Google that has strong support for concurrent programming. Its standard library (with a built-in HTTP server, JSON support, etc.) makes it a suitable backend language for scalable and high-performance web applications.
Go's concurrency model (using Goroutines and Channels) can handle multiple tasks simultaneously with minimal complexity.
Concepts
Keywords
package / import
/* The first line of every ~.go~ file specifies the package name. */
package main // declare main package (must contain main() function)
/* packages can be imported */
import "package"
import (
"fmt"
"time"
_ "embed" // mark package as unused
myname "github.com/path/to/library"
)
// private/public identifiers via capitalization
var foo := 3 // private to package
var Bar := 3 // will be exported
func DoThing() { /* ... */ } // can be called outside package
for, switch, range (Control flow)
switch state {
case 1:
goto label;
case 2:
fallthrough
case 3:
label: // goto label declaration
break // always implicitly there
default:
}
/* loops */
for count < 5 {
if count == 3 {
continue
}
}
for { /* ... */ } // like a while(true) loop
/* ranges */
scores := map[string]int{"Alice": 90, "Bob": 85}
for name, score := range scores {
/* ... */
}
Types
/* types */
var // declare a variable
const // declare a constant
map[string] // declare map type (hashtable/dictionary)
type Person struct { // define struct type
name string
age int
}
interface{} // any type
any // alias for interface{}
/* enums in go: use "iota" to declare constants */
type Weekday int
const (
_ = iota // ignore first value (iota == 0)
MONDAY Weekday = iota // == 1
TUESDAY // == 2
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
)
Functions/Interfaces
// functions
func example(var a int) (int, error) {
defer fmt.Printf("Finished\n") // defer function call to end of function
return a, nil
}
/* interfaces */
type Shape interface { // define interface named Shape
Area() float64
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 { // implement interface for Circle
return 3.14 * c.radius * c.radius
}
go, chan, select (Concurrency)
/* goroutines/channels */
go // start a goroutine
chan // declare channel type
select // wait on multiple channel operations
goroutine
A goroutine is a lightweight thread managed by the Go runtime.
package main
import (
"fmt"
"time"
)
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func main() {
go greet("Alice") // start goroutine
go greet("Bob") // start another
time.Sleep(1 * time.Second) // wait for goroutines to finish
fmt.Println("Finished.")
}
Using WaitGroup to wait for goroutine
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // notify that the goroutine is done
fmt.Printf("Worker %d starting\n", id)
time.Sleep(2 * time.Second) // simulate work
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1) // increment WaitGroup counter
go worker(i, &wg) // start goroutine
}
wg.Wait() // wait for all goroutines to finish
fmt.Println("All workers completed.")
}
chan (Channels)
Channels enable communication between goroutines.
package main
import "fmt"
func calculateSquare(num int, ch chan int) {
ch <- num * num // send result to channel
}
func main() {
ch := make(chan int) // create channel
for i := 1; i <= 5; i++ {
go calculateSquare(i, ch) // start goroutine
}
for i := 1; i <= 5; i++ {
fmt.Println("Square:", <-ch) // receive result from the channel
}
}
Channels can be directional:
var ch chan int // bidirectional (send & receive)
var sendCh chan<- int // send-only channel
var recvCh <-chan int // receive-only channel
Channels can be buffered or unbuffered:
- Buffered for synchronous, blocking communication
- Unbuffered for asynchronous, non-blocking communication
- Unbuffered better for coordination, buffered better for throughput
- Buffered can mask deadlocks that unbuffered would reveal
// Unbuffered channel
ch1 := make(chan int)
// - Synchronous communication
// - Sender blocks until receiver takes value
// - Receiver blocks until sender provides value
// - Provides guaranteed delivery and synchronization point
// Buffered channel
ch2 := make(chan int, 5) // Buffered with capacity 5
// - Asynchronous until buffer fills
// - Sender only blocks when buffer is full
// - Receiver blocks only when buffer is empty
// - Decouples sender and receiver timing
If no more messages need to be sent over the channel, it can be closed:
// sending side
close(ch) // close channel
val, ok := <-ch
if !ok {
// channel has closed (buffered channels stay open until emptied)
}
select
The select statement enables concurrent operations on channels.
Characteristics:
- Blocks until a channel operation can proceed
- Randomly selects if multiple cases are ready
- Can include non-blocking
defaultcase - Often used in goroutines for concurrent operations
- Can be combined with timeouts using
time.After()
select {
case <-ch1:
// Execute if data received from ch1
case x := <-ch2:
// Execute if data received from ch2, store in x
case ch3 <- value:
// Execute if data can be sent to ch3
case <-time.After(1 * time.Second):
fmt.Println("Timed out")
default:
// Execute if no other case is ready (optional)
}
Module System
go.mod:
The go.mod is the config file for a Go module.
- Declares module path (
module mymodule). - Declares required
goversion (go 1.21.1) - Lists module's dependencies (and versions) with
require (...) - Can include replace directives (useful for testing)
- Can also exclude modules
go.sum:
- The
go.sumfile is used to manage dependencies. - It contains the url for the module, its version and a cryptographic checksum.
- It is generated and updated when running
go get,go mod tidy, orgo build.
Idioms
Struct Embedding
Add types without a name to a struct to embed all of its members directly. The type can then call methods of that embedded type directly.
import "sync"
type Message struct {
sync.RWMutex
text string
}
func main() {
msg := Message{}
msg.Lock(); defer msg.Unlock();
}
Shorthand for Error Handling
if err := writer.Close(); err != nil {
panic(err)
}
Interface Satisfaction Check
Ensure a type implements interfaces at compile time:
var _ io.Reader = (*MyType)(nil)
If MyType doesn't implement Read(p []byte) (n int, err error), the compiler will
throw an error.