Skip to content

Instantly share code, notes, and snippets.

@miladjahandideh
Last active October 23, 2025 09:27
Show Gist options
  • Select an option

  • Save miladjahandideh/2a6d5d5e0f1b4c0021cf8a2d4bf8cb94 to your computer and use it in GitHub Desktop.

Select an option

Save miladjahandideh/2a6d5d5e0f1b4c0021cf8a2d4bf8cb94 to your computer and use it in GitHub Desktop.
Go Lang Review Notes
package main
import (
"bufio"
"context"
"crypto/md5"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
// ============================================================================
// CORE LANGUAGE FUNDAMENTALS
// ============================================================================
// Basic Syntax & Types
func basicSyntaxExample() {
fmt.Println("=== Basic Syntax & Types ===")
// Variable declarations
var name string = "Go"
var age int = 15
var isAwesome bool = true
// Short declaration
version := 1.21
// Constants and iota
const Pi = 3.14159
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
)
// Type conversions
var x int = 42
var y float64 = float64(x)
fmt.Printf("Name: %s, Age: %d, Awesome: %t, Version: %.2f\n", name, age, isAwesome, version)
fmt.Printf("Pi: %f, Sunday: %d, Converted: %f\n", Pi, Sunday, y)
}
// Control Flow
func controlFlowExample() {
fmt.Println("\n=== Control Flow ===")
// if/else (no parentheses needed)
x := 10
if x > 5 {
fmt.Println("x is greater than 5")
} else if x == 5 {
fmt.Println("x equals 5")
} else {
fmt.Println("x is less than 5")
}
// for loop (Go's only loop)
fmt.Print("Count: ")
for i := 0; i < 5; i++ {
fmt.Print(i, " ")
}
fmt.Println()
// for as while
count := 0
for count < 3 {
fmt.Printf("While-style loop: %d\n", count)
count++
}
// switch statement
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of work week")
case "Friday":
fmt.Println("TGIF!")
default:
fmt.Println("Regular day")
}
// defer example
defer fmt.Println("This prints last (deferred)")
fmt.Println("This prints first")
}
// ============================================================================
// GO-SPECIFIC FEATURES
// ============================================================================
// Functions
func functionExamples() {
fmt.Println("\n=== Functions ===")
// Multiple return values
result, err := divide(10, 2)
if err != nil {
fmt.Printf("Error: %v\n", err)
} else {
fmt.Printf("Division result: %d\n", result)
}
// Named return parameters
sum, product := calculate(4, 5)
fmt.Printf("Sum: %d, Product: %d\n", sum, product)
// Variadic function
total := addNumbers(1, 2, 3, 4, 5)
fmt.Printf("Total: %d\n", total)
// Function as variable
var operation func(int, int) int = func(a, b int) int {
return a * b
}
fmt.Printf("Anonymous function result: %d\n", operation(3, 4))
}
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named return parameters
func calculate(a, b int) (sum, product int) {
sum = a + b
product = a * b
return // naked return
}
// Variadic function
func addNumbers(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
// Pointers
func pointerExample() {
fmt.Println("\n=== Pointers ===")
x := 42
p := &x // p is a pointer to x
fmt.Printf("x = %d\n", x)
fmt.Printf("Address of x: %p\n", &x)
fmt.Printf("Pointer p: %p\n", p)
fmt.Printf("Value at pointer: %d\n", *p)
// Modify through pointer
*p = 100
fmt.Printf("x after modification through pointer: %d\n", x)
// Function with pointer parameter
increment(&x)
fmt.Printf("x after increment: %d\n", x)
}
func increment(n *int) {
*n++
}
// Structs and Methods
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
City string `json:"city"`
}
// Method with value receiver
func (p Person) Greet() string {
return fmt.Sprintf("Hello, I'm %s from %s", p.Name, p.City)
}
// Method with pointer receiver
func (p *Person) HaveBirthday() {
p.Age++
}
// Embedded struct (composition)
type Employee struct {
Person // embedded struct
Position string
Salary int
}
func structExample() {
fmt.Println("\n=== Structs and Methods ===")
// Struct initialization
person1 := Person{Name: "Alice", Age: 30, City: "New York"}
person2 := Person{"Bob", 25, "London"} // positional
fmt.Println(person1.Greet())
fmt.Println(person2.Greet())
// Method call
person1.HaveBirthday()
fmt.Printf("After birthday: %s is now %d\n", person1.Name, person1.Age)
// Embedded struct
emp := Employee{
Person: Person{Name: "Charlie", Age: 28, City: "Paris"},
Position: "Developer",
Salary: 75000,
}
fmt.Printf("Employee: %s, Position: %s\n", emp.Name, emp.Position)
// JSON marshaling (struct tags in action)
jsonData, _ := json.Marshal(person1)
fmt.Printf("JSON: %s\n", jsonData)
}
// ============================================================================
// ADVANCED CORE CONCEPTS
// ============================================================================
// Interfaces
type Writer interface {
Write(data string) error
}
type FileWriter struct {
filename string
}
func (fw FileWriter) Write(data string) error {
fmt.Printf("Writing '%s' to file: %s\n", data, fw.filename)
return nil
}
type ConsoleWriter struct{}
func (cw ConsoleWriter) Write(data string) error {
fmt.Printf("Console: %s\n", data)
return nil
}
func interfaceExample() {
fmt.Println("\n=== Interfaces ===")
var w Writer
// Interface implementation is implicit
w = FileWriter{filename: "output.txt"}
w.Write("Hello from file writer")
w = ConsoleWriter{}
w.Write("Hello from console writer")
// Empty interface
var anything interface{}
anything = 42
fmt.Printf("anything = %v (type: %T)\n", anything, anything)
anything = "hello"
fmt.Printf("anything = %v (type: %T)\n", anything, anything)
// Type assertion
if str, ok := anything.(string); ok {
fmt.Printf("Successfully asserted as string: %s\n", str)
}
}
// Slices and Arrays
func sliceExample() {
fmt.Println("\n=== Slices and Arrays ===")
// Array (fixed size)
var arr [5]int = [5]int{1, 2, 3, 4, 5}
fmt.Printf("Array: %v\n", arr)
// Slice (dynamic)
slice := []string{"apple", "banana", "cherry"}
fmt.Printf("Original slice: %v\n", slice)
// Slice operations
slice = append(slice, "date", "elderberry")
fmt.Printf("After append: %v\n", slice)
// Slicing
subSlice := slice[1:4]
fmt.Printf("Sub-slice [1:4]: %v\n", subSlice)
// Slice internals
fmt.Printf("Length: %d, Capacity: %d\n", len(slice), cap(slice))
// Make with capacity
numbers := make([]int, 3, 5) // length 3, capacity 5
numbers[0], numbers[1], numbers[2] = 10, 20, 30
fmt.Printf("Made slice: %v (len=%d, cap=%d)\n", numbers, len(numbers), cap(numbers))
}
// Maps
func mapExample() {
fmt.Println("\n=== Maps ===")
// Map declaration and initialization
colors := map[string]string{
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF",
}
fmt.Printf("Colors: %v\n", colors)
// Adding elements
colors["yellow"] = "#FFFF00"
// Checking for existence
if hex, exists := colors["purple"]; exists {
fmt.Printf("Purple: %s\n", hex)
} else {
fmt.Println("Purple not found")
}
// Deleting elements
delete(colors, "red")
fmt.Printf("After deleting red: %v\n", colors)
// Iterating over map
for color, hex := range colors {
fmt.Printf("%s: %s\n", color, hex)
}
}
// Channels and Goroutines
func channelExample() {
fmt.Println("\n=== Channels and Goroutines ===")
// Unbuffered channel
ch := make(chan string)
// Start a goroutine
go func() {
time.Sleep(1 * time.Second)
ch <- "Hello from goroutine!"
}()
// Receive from channel
message := <-ch
fmt.Println(message)
// Buffered channel
bufferedCh := make(chan int, 3)
bufferedCh <- 1
bufferedCh <- 2
bufferedCh <- 3
fmt.Printf("Buffered channel values: %d, %d, %d\n", <-bufferedCh, <-bufferedCh, <-bufferedCh)
// Channel with range and close
numberCh := make(chan int)
go func() {
for i := 1; i <= 5; i++ {
numberCh <- i
}
close(numberCh)
}()
fmt.Print("Numbers from channel: ")
for num := range numberCh {
fmt.Printf("%d ", num)
}
fmt.Println()
// Select statement
selectExample()
}
func selectExample() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
ch1 <- "from channel 1"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "from channel 2"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Printf("Received %s\n", msg1)
case msg2 := <-ch2:
fmt.Printf("Received %s\n", msg2)
case <-time.After(3 * time.Second):
fmt.Println("Timeout!")
}
}
}
// ============================================================================
// ERROR HANDLING AND MEMORY MANAGEMENT
// ============================================================================
// Custom error type
type ValidationError struct {
Field string
Message string
}
func (e ValidationError) Error() string {
return fmt.Sprintf("validation error in field '%s': %s", e.Field, e.Message)
}
func errorHandlingExample() {
fmt.Println("\n=== Error Handling ===")
// Basic error handling
result, err := riskyOperation(true)
if err != nil {
fmt.Printf("Error occurred: %v\n", err)
} else {
fmt.Printf("Success: %s\n", result)
}
// Custom error
err = validateAge(-5)
if err != nil {
fmt.Printf("Validation error: %v\n", err)
}
// Error wrapping (Go 1.13+)
err = processUser("invalid-user")
if err != nil {
fmt.Printf("Process error: %v\n", err)
}
// Panic and recover example
recoverExample()
}
func riskyOperation(shouldFail bool) (string, error) {
if shouldFail {
return "", errors.New("operation failed")
}
return "operation succeeded", nil
}
func validateAge(age int) error {
if age < 0 {
return ValidationError{
Field: "age",
Message: "must be non-negative",
}
}
return nil
}
func processUser(username string) error {
err := validateUsername(username)
if err != nil {
return fmt.Errorf("failed to process user: %w", err)
}
return nil
}
func validateUsername(username string) error {
if len(username) < 3 {
return errors.New("username too short")
}
return nil
}
func recoverExample() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered from panic: %v\n", r)
}
}()
fmt.Println("About to panic...")
panic("Something went wrong!")
fmt.Println("This won't print")
}
// ============================================================================
// PACKAGE SYSTEM AND TOOLING
// ============================================================================
// Package example would typically be in separate files, but here's the concept:
//
// In math/calculator.go:
// package math
//
// func Add(a, b int) int {
// return a + b
// }
//
// In main.go:
// import "myproject/math"
// result := math.Add(5, 3)
// ============================================================================
// TESTING AND DOCUMENTATION
// ============================================================================
// Example of how tests would look (in _test.go files):
//
// func TestAdd(t *testing.T) {
// result := Add(2, 3)
// if result != 5 {
// t.Errorf("Add(2, 3) = %d; want 5", result)
// }
// }
//
// func TestAddTableDriven(t *testing.T) {
// tests := []struct {
// a, b, expected int
// }{
// {2, 3, 5},
// {0, 0, 0},
// {-1, 1, 0},
// }
//
// for _, tt := range tests {
// result := Add(tt.a, tt.b)
// if result != tt.expected {
// t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
// }
// }
// }
//
// func BenchmarkAdd(b *testing.B) {
// for i := 0; i < b.N; i++ {
// Add(2, 3)
// }
// }
// ============================================================================
// CONCURRENCY PATTERNS
// ============================================================================
func concurrencyPatterns() {
fmt.Println("\n=== Concurrency Patterns ===")
// Worker pool pattern
workerPoolExample()
// Fan-in/Fan-out pattern
fanInOutExample()
// Context for cancellation
contextExample()
// Mutex example
mutexExample()
}
func workerPoolExample() {
fmt.Println("Worker Pool Pattern:")
jobs := make(chan int, 5)
results := make(chan int, 5)
// Start 3 workers
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// Send 5 jobs
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// Collect results
for a := 1; a <= 5; a++ {
<-results
}
}
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, j)
time.Sleep(100 * time.Millisecond)
results <- j * 2
}
}
func fanInOutExample() {
fmt.Println("Fan-in/Fan-out Pattern:")
input := make(chan int)
// Fan-out: distribute work to multiple goroutines
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
for n := range input {
if n%2 == 0 {
ch1 <- n
} else {
ch2 <- n
}
}
close(ch1)
close(ch2)
}()
// Send some numbers
go func() {
for i := 1; i <= 6; i++ {
input <- i
}
close(input)
}()
// Fan-in: merge results
output := fanIn(ch1, ch2)
for result := range output {
fmt.Printf("Processed: %d\n", result)
}
}
func fanIn(ch1, ch2 <-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for n := range ch1 {
out <- n * 10 // some processing
}
}()
go func() {
defer wg.Done()
for n := range ch2 {
out <- n * 100 // different processing
}
}()
go func() {
wg.Wait()
close(out)
}()
return out
}
func contextExample() {
fmt.Println("Context Example:")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case result := <-longRunningOperation(ctx):
fmt.Printf("Operation completed: %s\n", result)
case <-ctx.Done():
fmt.Printf("Operation cancelled: %v\n", ctx.Err())
}
}
func longRunningOperation(ctx context.Context) <-chan string {
result := make(chan string)
go func() {
defer close(result)
select {
case <-time.After(3 * time.Second):
result <- "operation completed"
case <-ctx.Done():
return
}
}()
return result
}
var counter int
var mutex sync.Mutex
func mutexExample() {
fmt.Println("Mutex Example:")
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mutex.Lock()
counter++
fmt.Printf("Counter: %d\n", counter)
mutex.Unlock()
}()
}
wg.Wait()
fmt.Printf("Final counter: %d\n", counter)
}
// ============================================================================
// STANDARD LIBRARY EXAMPLES
// ============================================================================
func standardLibraryExamples() {
fmt.Println("\n=== Standard Library Examples ===")
// strings package
text := " Hello, Go World! "
fmt.Printf("Original: '%s'\n", text)
fmt.Printf("Trimmed: '%s'\n", strings.TrimSpace(text))
fmt.Printf("Upper: '%s'\n", strings.ToUpper(text))
fmt.Printf("Contains 'Go': %t\n", strings.Contains(text, "Go"))
// strconv package
numStr := "42"
num, err := strconv.Atoi(numStr)
if err == nil {
fmt.Printf("Converted '%s' to %d\n", numStr, num)
}
// time package
now := time.Now()
fmt.Printf("Current time: %s\n", now.Format("2006-01-02 15:04:05"))
future := now.Add(24 * time.Hour)
fmt.Printf("24 hours later: %s\n", future.Format("January 2, 2006"))
// crypto/md5
data := "Hello, World!"
hash := md5.Sum([]byte(data))
fmt.Printf("MD5 of '%s': %x\n", data, hash)
// JSON encoding
person := Person{Name: "John", Age: 30, City: "Boston"}
jsonData, _ := json.Marshal(person)
fmt.Printf("JSON: %s\n", jsonData)
var decoded Person
json.Unmarshal(jsonData, &decoded)
fmt.Printf("Decoded: %+v\n", decoded)
}
// HTTP Server Example
func httpServerExample() {
fmt.Println("\n=== HTTP Server Example ===")
fmt.Println("Starting server on :8080 (this is just example code)")
// This would actually start a server:
// http.HandleFunc("/", homeHandler)
// http.HandleFunc("/api/users", usersHandler)
// log.Fatal(http.ListenAndServe(":8080", nil))
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to Go Web Server!")
}
func usersHandler(w http.ResponseWriter, r *http.Request) {
users := []Person{
{Name: "Alice", Age: 30, City: "New York"},
{Name: "Bob", Age: 25, City: "London"},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
// File I/O Example
func fileIOExample() {
fmt.Println("\n=== File I/O Example ===")
// Writing to file
content := "Hello from Go file I/O!"
err := os.WriteFile("example.txt", []byte(content), 0644)
if err != nil {
fmt.Printf("Error writing file: %v\n", err)
return
}
// Reading from file
data, err := os.ReadFile("example.txt")
if err != nil {
fmt.Printf("Error reading file: %v\n", err)
return
}
fmt.Printf("File content: %s\n", string(data))
// Reading with bufio
file, err := os.Open("example.txt")
if err != nil {
fmt.Printf("Error opening file: %v\n", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Printf("Line: %s\n", scanner.Text())
}
// Clean up
os.Remove("example.txt")
}
// Database Example (conceptual - would need actual DB)
func databaseExample() {
fmt.Println("\n=== Database Example (Conceptual) ===")
// This is how you'd typically work with SQL databases:
/*
db, err := sql.Open("postgres", "connection_string")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Query
rows, err := db.Query("SELECT name, age FROM users WHERE age > $1", 18)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
var age int
err := rows.Scan(&name, &age)
if err != nil {
log.Fatal(err)
}
fmt.Printf("User: %s, Age: %d\n", name, age)
}
// Insert
_, err = db.Exec("INSERT INTO users (name, age) VALUES ($1, $2)", "John", 25)
if err != nil {
log.Fatal(err)
}
*/
fmt.Println("Database operations would go here...")
}
// ============================================================================
// MAIN FUNCTION - DEMONSTRATES ALL CONCEPTS
// ============================================================================
func main() {
fmt.Println("=== GO PROGRAMMING CONCEPTS EXAMPLES ===")
// Core Language Fundamentals
basicSyntaxExample()
controlFlowExample()
// Go-Specific Features
functionExamples()
pointerExample()
structExample()
// Advanced Core Concepts
interfaceExample()
sliceExample()
mapExample()
channelExample()
// Error Handling
errorHandlingExample()
// Concurrency Patterns
concurrencyPatterns()
// Standard Library
standardLibraryExamples()
fileIOExample()
httpServerExample()
databaseExample()
fmt.Println("\n=== ALL EXAMPLES COMPLETED ===")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment