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
-
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
Category | Type | Zero Value (null) | Range |
---|---|---|---|
Boolean | bool | false | true or false |
Numeric Types | |||
Integer | int | 0 | 32-bit systems: -2^31 to 2^31-1 64-bit systems: -2^63 to 2^63-1 |
int8 | 0 | -128 to 127 (-2^7 to 2^7-1) | |
int16 | 0 | -32,768 to 32,767 (-2^15 to 2^15-1) | |
int32 | 0 | -2,147,483,648 to 2,147,483,647 (-2^31 to 2^31-1) | |
int64 | 0 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (-2^63 to 2^63-1) | |
Unsigned Integer | uint | 0 | 32-bit systems: 0 to 2^32-1 64-bit systems: 0 to 2^64-1 |
uint8 | 0 | 0 to 255 (0 to 2^8-1) | |
uint16 | 0 | 0 to 65,535 (0 to 2^16-1) | |
uint32 | 0 | 0 to 4,294,967,295 (0 to 2^32-1) | |
uint64 | 0 | 0 to 18,446,744,073,709,551,615 (0 to 2^64-1) | |
uintptr | 0 | 32-bit systems: 0 to 2^32-1 64-bit systems: 0 to 2^64-1 | |
Float | float32 | 0.0 | ±1.18E-38 to ±3.4E38 |
float64 | 0.0 | ±2.23E-308 to ±1.80E308 | |
Complex | complex64 | 0+0i | Real and imaginary parts are float32 |
complex128 | 0+0i | Real and imaginary parts are float64 | |
String | string | "" | 0 to 2^31-1 bytes (limited by max slice size) |
Pointer | *T | nil | Memory address space |
Reference Types | |||
Slice | []T | nil | 0 to 2^31-1 elements (implementation dependent) |
Map | map[K]V | nil | Limited by available memory |
Channel | chan T | nil | Buffer size limited by available memory |
Interface | interface{} | nil | N/A |
Function | func() | nil | N/A |
Composite Types | |||
Struct | struct{} | Zero value of each field | Depends on field types |
Array | [n]T | Array of zero values | Fixed size defined at declaration |
Additional notes
-
Memory Usage:
string
: Each string takes 16 bytes overhead plus actual string dataslice
: 24 bytes overhead plus underlying arraymap
: Implementation dependent, but has overhead per entry
-
Platform Dependencies:
int
,uint
, anduintptr
sizes depend on the platform (32 or 64 bit)- Memory addresses and maximum slice sizes are platform dependent
-
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
-
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)
}
}