Skip to main content

Go lang

  • Open-source programming language developed by Google
  • Features
    • Focus on simplicity, clarity & scalability
    • High performance + Concurrency
    • Batteries included (core features built-in)
    • Static typing (type-sade)
  • Use case
    • Networking & APIs
    • Microservices
    • CLI Tools

Setting

  • Official page

  • Check version

    go version
  • First Go program

    package main
    import "fmt"
    func main() {
    fmt.Println("Hello, World!")
    }
    go run <filename>.go

Variables & Data Types

Go can automatically infer types with the short-hand declaration.

Declare

var x int = 10
y := 20 // short hand

Basic Types

var age int = 30
var name string = "John"
var isActive bool = true
CategoryTypeZero Value (null)Range
Booleanboolfalsetrue or false
Numeric Types
Integerint032-bit systems: -2^31 to 2^31-1
64-bit systems: -2^63 to 2^63-1
int80-128 to 127
(-2^7 to 2^7-1)
int160-32,768 to 32,767
(-2^15 to 2^15-1)
int320-2,147,483,648 to 2,147,483,647
(-2^31 to 2^31-1)
int640-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
(-2^63 to 2^63-1)
Unsigned Integeruint032-bit systems: 0 to 2^32-1
64-bit systems: 0 to 2^64-1
uint800 to 255
(0 to 2^8-1)
uint1600 to 65,535
(0 to 2^16-1)
uint3200 to 4,294,967,295
(0 to 2^32-1)
uint6400 to 18,446,744,073,709,551,615
(0 to 2^64-1)
uintptr032-bit systems: 0 to 2^32-1
64-bit systems: 0 to 2^64-1
Floatfloat320.0±1.18E-38 to ±3.4E38
float640.0±2.23E-308 to ±1.80E308
Complexcomplex640+0iReal and imaginary parts are float32
complex1280+0iReal and imaginary parts are float64
Stringstring""0 to 2^31-1 bytes
(limited by max slice size)
Pointer*TnilMemory address space
Reference Types
Slice[]Tnil0 to 2^31-1 elements
(implementation dependent)
Mapmap[K]VnilLimited by available memory
Channelchan TnilBuffer size limited by available memory
Interfaceinterface{}nilN/A
Functionfunc()nilN/A
Composite Types
Structstruct{}Zero value of each fieldDepends on field types
Array[n]TArray of zero valuesFixed size defined at declaration
Additional notes
  1. Memory Usage:

    • string: Each string takes 16 bytes overhead plus actual string data
    • slice: 24 bytes overhead plus underlying array
    • map: Implementation dependent, but has overhead per entry
  2. Platform Dependencies:

    • int, uint, and uintptr sizes depend on the platform (32 or 64 bit)
    • Memory addresses and maximum slice sizes are platform dependent
  3. Special Considerations:

    • Floats: Follow IEEE-754 standard
    • Strings: Immutable UTF-8 encoded
    • Maps: Must be initialized with make() before use
    • Channels: Must be initialized with make() before use
  4. SQL Nullable Types:

    sql.NullString    // For nullable string
    sql.NullInt64 // For nullable int64
    sql.NullFloat64 // For nullable float64
    sql.NullBool // For nullable bool
    sql.NullTime // For nullable time.Time

Control flow

Conditional

if age > 18 {
fmt.Println("Adult")
} else if (age > 14) {
fmt.Println("Minor")
} else {
fmt.Println("Child")
}

switch day {
case "Monday":
fmt.Println("Start of the week")
default:
fmt.Println("Other day")
}

Loops

// declare; condition; update
for i := 0; i < 5; i++ {
fmt.Println(i)
}

// Infinity -> for condition {}
for {
// do something and break
}

// Use with switch
outer:
for userInput != 0 {
switch userInput {
case 1:
// something
// ...
default:
break outer // exit loop
}
}

Functions

func add(x int, y int) int {
return x + y
}

func getUserInput(info string) (value float32) {
fmt.Print(info)
fmt.Scan(&value)
return value
}
// Multiple return values
func swap(a, b string) (string, string) {
return b, a
}

// constraint variable's name
func calculateFinancials(revenue float32, expenses float32, taxRate float32) (ebt float32, profit float32, ratio float32) {
ebt = revenue - expenses // Earn Before Tax
profit = ebt * (1 - taxRate/100)
ratio = ebt / profit

return ebt, profit, ratio
}

Data structures

Array & Slice

// Arrays are fixed-length, while Slices are dynamic
var arr = [3]int{1, 2, 3}
var slice = []int{1, 2, 3, 4, 5}

Map

m := map[string]int{"apple": 1, "banana": 2}

Structs & Methods

// Structs are used to group related data together
type Person struct {
Name string
Age int
}

// Using
func (p Person) Greet() {
fmt.Println("Hello, my name is", p.Name)
}

Error handling

// Go uses explicit error handling with the error type.
func divide(x, y float64) (float64, error) {
if y == 0 {
return 0, fmt.Errorf("cannot divide by zero")
}
return x / y, nil
}

// This will stop the program and print the error message to the console
panic("Something went wrong!")
// defer & recover
defer fmt.Println("End of program")

Concurrency

// Goroutine - Lightweight threads managed by Go
go func() {
fmt.Println("Running in a goroutine")
}()

// Use channels to communicate between goroutines
c := make(chan string)
go func() { c <- "Hello from goroutine" }()
fmt.Println(<-c)

Tesing

func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("expected 5, got %d", result)
}
}

Resources