Go
This is my github repo for learning go and storing notes for future references...
Install / Use
/learn @Hardik180704/GoREADME
<div align="center">
<img src="https://go.dev/blog/go-brand/Go-Logo/PNG/Go-Logo_Blue.png" alt="Go Logo" width="200"/>
📚 Complete Go Programming Guide
From Basics to Advanced - Your Ultimate Reference
</div>📖 Table of Contents
- 1. Introduction to Go
- 2. Getting Started
- 3. Basic Syntax
- 4. Variables & Data Types
- 5. Control Flow
- 6. Functions
- 7. Arrays & Slices
- 8. Maps
- 9. Structs
- 10. Pointers
- 11. Methods & Interfaces
- 12. Error Handling
- 13. Goroutines
- 14. Channels
- 15. Mutex & Synchronization
- 16. File Handling
- 17. Packages & Modules
- 18. Testing
- 19. Best Practices
- 20. Resources
1. Introduction to Go
1.1 What is Go?
Go (also called Golang) is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson.
Key Features:
- ✅ Simple & Clean - Easy to learn syntax
- ✅ Fast Compilation - Compiles to native machine code
- ✅ Built-in Concurrency - Goroutines and channels
- ✅ Garbage Collection - Automatic memory management
- ✅ Strong Standard Library - Rich built-in packages
- ✅ Cross-Platform - Compile for Windows, Mac, Linux
1.2 Why Use Go?
Perfect For:
- 🌐 Web servers and APIs
- ☁️ Cloud-native applications
- 🔧 Command-line tools
- 🚀 Microservices
- 📊 Data pipelines
- 🤖 DevOps tools
Companies Using Go:
- Uber
- Netflix
- Docker
- Kubernetes
- Dropbox
2. Getting Started
2.1 Installation
Download Go:
# Visit: https://go.dev/dl/
# Or use package manager:
# macOS
brew install go
# Linux (Ubuntu/Debian)
sudo apt install golang-go
# Windows
# Download installer from go.dev
Verify Installation:
go version
# Output: go version go1.21.0 darwin/amd64
2.2 Your First Program
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Run it:
go run main.go
# Output: Hello, World!
Compile it:
go build main.go
./main
2.3 Project Structure
myproject/
├── go.mod # Module definition
├── go.sum # Dependency checksums
├── main.go # Entry point
├── internal/ # Private packages
├── pkg/ # Public packages
└── cmd/ # Command-line apps
3. Basic Syntax
3.1 Package Declaration
package main // Executable program
package utils // Library/module
Rules:
- Every Go file starts with
package mainpackage = executable- Other packages = libraries
3.2 Import Statements
// Single import
import "fmt"
// Multiple imports
import (
"fmt"
"strings"
"time"
)
// Custom packages
import (
"github.com/username/repo/package"
)
3.3 Comments
// Single-line comment
/*
Multi-line
comment
*/
// Documentation comment (appears in godoc)
// Package math provides mathematical functions.
package math
3.4 Semicolons
Go automatically inserts semicolons - you don't write them!
// No semicolons needed
x := 5
y := 10
z := x + y
4. Variables & Data Types
4.1 Variable Declaration
// Method 1: var keyword
var name string = "Hardik"
var age int = 25
// Method 2: Type inference
var city = "Mumbai" // Type inferred as string
// Method 3: Short declaration (MOST COMMON)
email := "hardik@example.com"
count := 42
Rules:
:=only works inside functions- Cannot redeclare with
:= - Can only use
varat package level
4.2 Data Types
Basic Types
// Boolean
var isActive bool = true
// String
var name string = "Go"
// Integer types
var age int = 25 // Platform-dependent (32 or 64 bit)
var count int8 = 127 // -128 to 127
var id int16 = 32767 // -32768 to 32767
var bigNum int32 = 2147483647
var huge int64 = 9223372036854775807
// Unsigned integers
var positive uint = 42 // Only positive numbers
var small uint8 = 255 // 0 to 255 (also called byte)
// Floating point
var price float32 = 19.99
var precise float64 = 3.14159265359
// Complex numbers
var complex64Num complex64 = 1 + 2i
var complex128Num complex128 = 2 + 3i
// Byte (alias for uint8)
var b byte = 'A' // ASCII value: 65
// Rune (alias for int32) - Unicode code point
var r rune = '😀'
Zero Values
var i int // 0
var f float64 // 0.0
var b bool // false
var s string // "" (empty string)
var p *int // nil
4.3 Constants
// Single constant
const Pi = 3.14159
// Multiple constants
const (
StatusOK = 200
StatusNotFound = 404
StatusError = 500
)
// Typed constants
const MaxUsers int = 1000
// iota - auto-incrementing
const (
Monday = iota // 0
Tuesday // 1
Wednesday // 2
Thursday // 3
Friday // 4
)
4.4 Type Conversion
var x int = 42
var y float64 = float64(x) // Explicit conversion required
var a float64 = 10.5
var b int = int(a) // b = 10 (truncates)
// String conversion
import "strconv"
str := strconv.Itoa(42) // "42"
num, _ := strconv.Atoi("42") // 42
5. Control Flow
5.1 If-Else
// Basic if
if age >= 18 {
fmt.Println("Adult")
}
// If-else
if score >= 90 {
fmt.Println("Grade A")
} else if score >= 80 {
fmt.Println("Grade B")
} else {
fmt.Println("Grade C")
}
// If with short statement
if err := someFunction(); err != nil {
fmt.Println("Error:", err)
}
5.2 Switch
// Basic switch
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of week")
case "Friday":
fmt.Println("End of week")
default:
fmt.Println("Middle of week")
}
// Multiple cases
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend!")
}
// Switch without expression (like if-else)
score := 85
switch {
case score >= 90:
fmt.Println("Excellent")
case score >= 70:
fmt.Println("Good")
default:
fmt.Println("Needs improvement")
}
// Type switch
var i interface{} = "hello"
switch v := i.(type) {
case int:
fmt.Printf("Integer: %d\n", v)
case string:
fmt.Printf("String: %s\n", v)
default:
fmt.Printf("Unknown type: %T\n", v)
}
5.3 Loops
Go has only one loop keyword: for
// Standard for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-style loop
count := 0
for count < 5 {
fmt.Println(count)
count++
}
// Infinite loop
for {
fmt.Println("Forever...")
break // Use break to exit
}
// Range loop (arrays, slices, maps)
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
// Range with only value
for _, value := range numbers {
fmt.Println(value)
}
// Range over string (gets runes)
for i, char := range "Hello" {
fmt.Printf("%d: %c\n", i, char)
}
5.4 Break & Continue
// Break - exit loop
for i := 0; i < 10; i++ {
if i == 5 {
break // Stops at 5
}
fmt.Println(i)
}
// Continue - skip iteration
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue // Skip even numbers
}
fmt.Println(i) // Prints only odd numbers
}
// Labeled break (break outer loop)
outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == 1 && j == 1 {
break outer
}
fmt.Printf("i=%d, j=%d\n", i, j)
}
}
6. Functions
6.1 Basic Functions
// Simple function
func greet() {
fmt.Println("Hello!")
}
// Function with parameters
func add(a int, b int) int {
return a + b
}
// Shorthand for same type parameters
func multiply(a, b, c int) int {
return a * b * c
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Named return values
func calculate(a, b int) (sum int, product int) {
sum = a + b
product = a * b
return // Naked return
}
6.2 Variadic Functions
// Accept any number of arguments
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
// Usage
result := sum(1, 2, 3, 4, 5) // 15
6.3 Anonymous Functions
// Assign to variable
add := func(a, b int) int {
return a + b
}
result := add(5, 3)
// Immediately invoked
func() {
fmt.Println("I run immediately!")
}()
6.4 Closures
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Usage
increment := counter()
fmt.Println(increment()) // 1
fmt.Println(increment()) // 2
fmt.Println(increment()) // 3
6.5 Defer
// Deferred function runs AFTER surrounding function returns
func example() {
defer fmt.Println("World") // Runs last
fmt.Println("Hello") // Runs first
}
// Output: Hello World
// Common use: Clean up resources
func readFile(filename string) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close() // Ensures file closes
// Read file...
}
// Multiple defers (LIFO - Last In First Out)
func stacking() {
defer fmt.Println("1")
defer fmt.Println("2")
de
