Go (Golang) Documentation
Simple, fast and built for concurrency — powers Docker, Kubernetes and many cloud backends.
Go is a simple, compiled, statically typed language created at Google. It compiles to a single fast binary, has a garbage collector, and makes concurrency easy with goroutines and channels. Docker, Kubernetes, Terraform and many cloud backends are written in Go.
1. Introduction & Installation
Download the installer from go.dev/dl (Windows/macOS) or use your package manager (sudo apt install golang-go, brew install go).
go version
mkdir hello && cd hello
go mod init example.com/hello # creates go.mod (your module)
go run main.go # compile + run
go build # builds an executable
package main
import "fmt"
func main() {
fmt.Println("Hello, Codify!")
}
Output:
Hello, Codify!
go fmt formats your code, go vet finds suspicious code, go test runs tests and go get adds dependencies.
⚠️ Common error:
go: cannot find main module— rungo mod init <name>in the project folder first.
2. Basic Syntax
- Every file starts with
package; an executable needspackage mainandfunc main(). - No semicolons; the opening
{must be on the same line. - Unused variables and imports are compile errors — Go keeps code clean.
- Exported names start with a capital letter (
fmt.Println); lowercase names are private to the package.
package main
import (
"fmt"
"strings"
)
func main() {
name := "gopher" // short declaration (inside functions)
fmt.Println(strings.ToUpper(name), len(name))
fmt.Printf("%s has %d letters\n", name, len(name))
}
Output:
GOPHER 6
gopher has 6 letters
⚠️ Common error:
declared and not used: x— remove the variable or use_ = xwhile debugging.
3. Variables & Data Types
| Type | Example |
|---|---|
int, int64, uint8 (byte) |
var n int = 42 |
float64 |
pi := 3.14 |
string |
"text" (immutable, UTF-8) |
rune |
'A' (a Unicode code point, alias for int32) |
bool |
true, false |
| composite | arrays, slices, maps, structs, pointers, channels, functions, interfaces |
Unassigned variables get their zero value: 0, "", false, nil.
package main
import (
"fmt"
"strconv"
)
const Pi = 3.14159
func main() {
var age int = 21
var price = 99.5 // type inferred: float64
city := "Pune"
var count int // zero value 0
var ok bool // false
r := 'G'
n, _ := strconv.Atoi("123")
f := 7.9
fmt.Println(age, price, city, count, ok, r, string(r))
fmt.Println(n+1, strconv.Itoa(45)+"!", float64(age)/2, int(f)) // int() truncates
fmt.Printf("%T %T %T %.2f\n", age, price, city, Pi)
}
Output:
21 99.5 Pune 0 false 71 G
124 45! 10.5 7
int float64 string 3.14
⚠️ Common error:
mismatched types int and float64— Go never converts automatically. Convert explicitly:float64(a) / b. Also,int(7.9)on a constant is a compile error — conversion that loses data only works on variables.
4. Operators
Arithmetic + - * / % (integer / truncates), comparison == != < > <= >=, logical && || !, bitwise & | ^ &^ << >>, assignment = += -= ..., and ++/-- as statements (not expressions). There is no ternary operator.
package main
import "fmt"
func main() {
a, b := 17, 5
fmt.Println(a/b, a%b, -17/5, float64(a)/float64(b))
fmt.Println(a > b && b > 0, !(a == 17))
fmt.Println(6&3, 6|3, 6^3, 1<<10, 12&^4)
a++
fmt.Println(a)
}
Output:
3 2 -3 3.4
true false
2 7 5 1024 8
18
⚠️ Common error:
x := y++—++is a statement in Go, not an expression.
5. Conditional Statements
package main
import "fmt"
func grade(marks int) string {
if marks >= 90 {
return "A"
} else if marks >= 75 {
return "B"
}
return "C"
}
func main() {
fmt.Println(grade(82))
if n := 7; n%2 == 0 { // short statement before the condition
fmt.Println(n, "is even")
} else {
fmt.Println(n, "is odd")
}
day := "sat"
switch day { // no break needed; cases don't fall through
case "sat", "sun":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
temp := 31
switch { // switch without a value = if/else chain
case temp > 35:
fmt.Println("hot")
case temp > 25:
fmt.Println("warm")
default:
fmt.Println("cool")
}
}
Output:
B
7 is odd
weekend
warm
⚠️ Common error: conditions must be
bool—if n { }with an int doesn't compile. Writeif n != 0.
6. Loops
Go has only one loop keyword: for.
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ { // classic
fmt.Print(i, " ")
}
fmt.Println()
n := 1
for n < 100 { // like while
n *= 2
}
fmt.Println("n =", n)
langs := []string{"go", "rust", "c"}
for i, l := range langs { // index and value
fmt.Println(i, l)
}
for _, ch := range "héllo" { // range over a string gives runes
fmt.Printf("%c ", ch)
}
fmt.Println()
count := 0
for { // infinite loop
count++
if count == 3 {
break
}
}
fmt.Println("count =", count)
}
Output:
1 2 3
n = 128
0 go
1 rust
2 c
h é l l o
count = 3
⚠️ Common error: taking
&vof the range variable inside the loop and storing it — before Go 1.22 every pointer pointed to the same variable. Go 1.22+ creates a new variable per iteration.
7. Functions
package main
import (
"errors"
"fmt"
)
func add(a, b int) int { return a + b }
func divmod(a, b int) (int, int) { // multiple return values
return a / b, a % b
}
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func sum(nums ...int) (total int) { // variadic + named result
for _, n := range nums {
total += n
}
return
}
func counter() func() int { // closure
c := 0
return func() int { c++; return c }
}
func main() {
q, r := divmod(17, 5)
fmt.Println(add(2, 3), q, r, sum(1, 2, 3, 4))
if _, err := divide(1, 0); err != nil {
fmt.Println("error:", err)
}
next := counter()
next()
fmt.Println(next())
defer fmt.Println("deferred: runs last")
fmt.Println("main body")
}
Output:
5 3 2 10
error: division by zero
2
main body
deferred: runs last
⚠️ Common error: ignoring the returned
error. In Go, errors are values — always checkif err != nil.
8. Arrays & Data Structures
Arrays have a fixed size ([3]int); slices ([]int) are dynamic views over arrays and are what you use 99% of the time. Maps are hash tables.
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
arr := [3]int{1, 2, 3}
s := []int{5, 2, 8}
s = append(s, 1, 9)
sort.Ints(s)
fmt.Println(arr, s, len(s), s[1:3])
grid := make([][]int, 2) // 2-D slice
for i := range grid {
grid[i] = make([]int, 3)
}
grid[1][2] = 7
fmt.Println(grid)
ages := map[string]int{"asha": 21, "ravi": 23}
ages["neha"] = 22
if a, ok := ages["john"]; !ok { // "comma ok" idiom
fmt.Println("john missing", a)
}
delete(ages, "ravi")
keys := make([]string, 0, len(ages))
for k := range ages {
keys = append(keys, k)
}
sort.Strings(keys) // map order is random — sort to print
fmt.Println(keys, len(ages))
words := strings.Fields("go is fun and go is fast")
freq := map[string]int{}
for _, w := range words {
freq[w]++
}
fmt.Println(freq["go"], freq["is"], freq["fun"])
}
Output:
[1 2 3] [1 2 5 8 9] 5 [2 5]
[[0 0 0] [0 0 7]]
john missing 0
[asha neha] 2
2 2 1
⚠️ Common error:
panic: assignment to entry in nil map—var m map[string]intis nil. Create it withmake(map[string]int)or a literal.
9. Object-Oriented Programming
Go has no classes or inheritance. It uses structs + methods for data and behaviour, embedding for reuse, and interfaces (satisfied implicitly) for polymorphism.
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Name() string
}
type Rect struct{ W, H float64 }
type Circle struct{ R float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string { return "rect" }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Name() string { return "circle" }
type Account struct {
Owner string
balance float64 // lowercase: private to the package
}
func (a *Account) Deposit(x float64) { a.balance += x } // pointer receiver modifies the struct
func (a Account) Balance() float64 { return a.balance }
type Savings struct {
Account // embedding: Savings gets Account's fields and methods
Rate float64
}
func main() {
shapes := []Shape{Rect{3, 4}, Circle{1}}
for _, s := range shapes {
fmt.Printf("%s %.2f\n", s.Name(), s.Area())
}
sv := Savings{Account{Owner: "Asha"}, 0.04}
sv.Deposit(1000)
fmt.Println(sv.Owner, sv.Balance(), sv.Rate)
}
Output:
rect 12.00
circle 3.14
Asha 1000 0.04
⚠️ Common error: a value receiver (
func (a Account) Deposit) changes a copy. Use a pointer receiver(a *Account)to modify the original.
10. Advanced Concepts
Goroutines and channels — go f() starts a lightweight concurrent function; channels pass values safely between goroutines:
package main
import (
"fmt"
"sync"
)
func square(n int, out chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
out <- n * n
}
func main() {
nums := []int{1, 2, 3, 4, 5}
out := make(chan int, len(nums)) // buffered channel
var wg sync.WaitGroup
for _, n := range nums {
wg.Add(1)
go square(n, out, &wg)
}
wg.Wait()
close(out)
total := 0
for v := range out {
total += v
}
fmt.Println("sum of squares:", total)
}
sum of squares: 55
Use select to wait on several channels, sync.Mutex to protect shared data, and context.Context for timeouts/cancellation. Run go run -race . to detect data races.
Error handling — wrap errors with context and check them with errors.Is:
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func findUser(id int) (string, error) {
if id != 1 {
return "", fmt.Errorf("findUser(%d): %w", id, ErrNotFound)
}
return "asha", nil
}
func main() {
_, err := findUser(7)
fmt.Println(err, errors.Is(err, ErrNotFound))
}
findUser(7): not found true
HTTP server with the standard library:
package main
import (
"encoding/json"
"net/http"
)
func main() {
http.HandleFunc("/api/hello", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "Hello from Go"})
})
http.ListenAndServe(":8080", nil) // open http://localhost:8080/api/hello
}
Also learn: generics (func Map[T, U any](s []T, f func(T) U) []U), panic/recover, testing with go test, and modules/packages.
11. Examples with Output
Example 1 — Reverse a string (rune-safe)
package main
import "fmt"
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func main() {
fmt.Println(reverse("Codify"), reverse("नमस्ते") != "")
}
yfidoC true
Example 2 — Generic Map function
package main
import (
"fmt"
"strings"
)
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, it := range items {
out = append(out, f(it))
}
return out
}
func main() {
fmt.Println(Map([]int{1, 2, 3}, func(n int) int { return n * n }))
fmt.Println(Map([]string{"go", "c"}, strings.ToUpper))
}
[1 4 9]
[GO C]
Example 3 — Worker pool
package main
import (
"fmt"
"sort"
"sync"
)
func main() {
jobs := make(chan int, 10)
results := make(chan string, 10)
var wg sync.WaitGroup
for w := 1; w <= 3; w++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
for j := range jobs {
results <- fmt.Sprintf("job %d done", j)
}
}(w)
}
for j := 1; j <= 4; j++ {
jobs <- j
}
close(jobs)
wg.Wait()
close(results)
var all []string
for r := range results {
all = append(all, r)
}
sort.Strings(all)
fmt.Println(len(all), all[0], all[3])
}
4 job 1 done job 4 done
12. Practice Problems
- Read numbers from standard input with
bufio.Scannerand print their sum and maximum. - Write
isPalindrome(s string) boolthat ignores case and non-letters. - Count word frequencies in a sentence with a
map[string]intand print them sorted by count. - Implement a stack and a queue using slices, with methods on a struct.
- Define a
Shapeinterface and three shapes; sort them by area withsort.Slice. - Fetch three URLs concurrently with goroutines and print their status codes.
- Build a tiny REST API (
GET /todos,POST /todos) withnet/httpand JSON. - Solve the logic of Two Sum and Valid Parentheses in Go (then submit in C++/Java/Python on Codify).
13. Interview Questions
1. What makes Go good for backend services? Fast compilation, a single static binary, a strong standard library (HTTP, JSON), garbage collection and built-in concurrency with goroutines.
2. Goroutine vs OS thread? Goroutines are managed by the Go runtime, start with a tiny (~2 KB) growable stack and are multiplexed onto a few OS threads — you can run hundreds of thousands.
3. What is a channel? Buffered vs unbuffered? A typed pipe between goroutines. Unbuffered channels block until sender and receiver are both ready; buffered ones block only when full/empty.
4. Array vs slice?
An array has a fixed length that is part of its type. A slice is a (pointer, length, capacity) view over an array that can grow with append.
5. How does Go handle errors?
Functions return an error value as the last result; callers check if err != nil. panic is for unrecoverable situations.
6. How do interfaces work in Go?
They are satisfied implicitly — any type with the required methods implements the interface, no implements keyword.
7. What does defer do?
Schedules a call to run when the surrounding function returns (LIFO order) — used for closing files, unlocking mutexes, etc.
8. Value vs pointer receivers? Value receivers get a copy; pointer receivers can modify the original and avoid copying large structs.
9. What is select?
A switch for channel operations — it waits until one of several sends/receives can proceed (with an optional default).
10. What is the zero value?
The default value of a declared but unassigned variable: 0, "", false, or nil for pointers, slices, maps, channels, functions and interfaces.
14. Cheat Sheet & References
Project and tools
# new module, run, build, test, format
go mod init example.com/app
go run .
go build -o app
go test ./...
go fmt ./... && go vet ./...
go get github.com/gin-gonic/gin
Basics
var x int = 5; y := 10; const Pi = 3.14
fmt.Println(a, b); fmt.Printf("%d %s %v %.2f\n", n, s, v, f)
s := fmt.Sprintf("id-%03d", 7)
n, err := strconv.Atoi("42"); str := strconv.Itoa(42)
Control flow
if v, ok := m[k]; ok { }
for i := 0; i < n; i++ { }
for cond { }
for i, v := range slice { }
switch x { case 1, 2: default: }
Slices and maps
s := []int{1, 2}; s = append(s, 3); s[1:3]; len(s); cap(s)
s := make([]int, n)
copy(dst, src)
sort.Ints(s); sort.Slice(p, func(i, j int) bool { return p[i].Age < p[j].Age })
m := map[string]int{}; m["a"] = 1; delete(m, "a"); v, ok := m["a"]
Structs, methods, interfaces
type User struct { Name string; Age int }
func (u *User) Birthday() { u.Age++ }
type Speaker interface { Speak() string }
u := &User{Name: "Asha"}
Errors
if err != nil { return fmt.Errorf("load config: %w", err) }
errors.Is(err, ErrNotFound); errors.New("msg")
defer f.Close()
Concurrency
go work()
ch := make(chan int, 10); ch <- 1; v := <-ch; close(ch)
var wg sync.WaitGroup; wg.Add(1); defer wg.Done(); wg.Wait()
var mu sync.Mutex; mu.Lock(); mu.Unlock()
select { case v := <-ch: case <-time.After(time.Second): }
Official documentation