Go Examples

Go syntax highlighting

Go Syntax Highlighting

Hello World

Example:

package main import "fmt" func main() { fmt.Println("Hello, World!") }

Variables and Types

Example:

package main import "fmt" func main() { // Basic types var name string = "Go" var version float64 = 1.21 var isAwesome bool = true // Short variable declaration count := 42 pi := 3.14159 // Multiple types var ( age int = 25 height float32 = 5.9 initial rune = 'G' ) // Integer variants var smallInt int8 = 127 var bigInt int64 = 9223372036854775807 var unsigned uint = 42 var ptr uintptr = 0xFF // Complex numbers var complex1 complex64 = 1 + 2i var complex2 complex128 = 3 + 4i fmt.Printf("Name: %s, Version: %.2f, Awesome: %v\n", name, version, isAwesome) }

Structs and Methods

Example:

package main import "fmt" // Person represents a person with name and age type Person struct { Name string Age int } // Greet is a method on Person func (p Person) Greet() string { return fmt.Sprintf("Hello, I'm %s and I'm %d years old", p.Name, p.Age) } // UpdateAge updates the person's age (pointer receiver) func (p *Person) UpdateAge(newAge int) { p.Age = newAge } func main() { person := Person{Name: "Alice", Age: 30} fmt.Println(person.Greet()) person.UpdateAge(31) fmt.Println(person.Greet()) }

Interfaces

Example:

package main import ( "fmt" "math" ) // Shape is an interface for geometric shapes type Shape interface { Area() float64 Perimeter() float64 } type Circle struct { Radius float64 } func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius } func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius } type Rectangle struct { Width, Height float64 } func (r Rectangle) Area() float64 { return r.Width * r.Height } func (r Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height) } func printShapeInfo(s Shape) { fmt.Printf("Area: %.2f, Perimeter: %.2f\n", s.Area(), s.Perimeter()) } func main() { circle := Circle{Radius: 5} rectangle := Rectangle{Width: 4, Height: 6} printShapeInfo(circle) printShapeInfo(rectangle) }

Goroutines and Channels

Example:

package main import ( "fmt" "time" ) func worker(id int, jobs <-chan int, results chan<- int) { for job := range jobs { fmt.Printf("Worker %d processing job %d\n", id, job) time.Sleep(time.Second) results <- job * 2 } } func main() { const numJobs = 5 jobs := make(chan int, numJobs) results := make(chan int, numJobs) // Start 3 workers for w := 1; w <= 3; w++ { go worker(w, jobs, results) } // Send jobs for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) // Collect results for a := 1; a <= numJobs; a++ { <-results } }

Error Handling

Example:

package main import ( "errors" "fmt" ) func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { // Successful division result, err := divide(10, 2) if err != nil { panic(err) } fmt.Printf("10 / 2 = %.2f\n", result) // Division by zero _, err = divide(10, 0) if err != nil { fmt.Println("Error:", err) } // Defer, panic, and recover defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() // This would panic without the recover above // panic("Something went wrong!") }

Slices and Maps

Example:

package main import "fmt" func main() { // Slices numbers := []int{1, 2, 3, 4, 5} numbers = append(numbers, 6, 7, 8) fmt.Println("Length:", len(numbers)) fmt.Println("Capacity:", cap(numbers)) fmt.Println("First three:", numbers[:3]) // Make a slice with capacity slice := make([]string, 0, 10) slice = append(slice, "Go", "is", "awesome") // Maps ages := map[string]int{ "Alice": 30, "Bob": 25, "Carol": 28, } ages["David"] = 32 // Check if key exists age, exists := ages["Alice"] if exists { fmt.Printf("Alice is %d years old\n", age) } // Range over map for name, age := range ages { fmt.Printf("%s: %d\n", name, age) } delete(ages, "Bob") }

Control Flow

Example:

package main import "fmt" func main() { // For loops for i := 0; i < 5; i++ { fmt.Println(i) } // While-style loop count := 0 for count < 3 { fmt.Println("Count:", count) count++ } // Infinite loop with break sum := 0 for { sum++ if sum > 10 { break } } // Range over slice fruits := []string{"apple", "banana", "cherry"} for index, fruit := range fruits { fmt.Printf("%d: %s\n", index, fruit) } // Switch statement day := "Monday" switch day { case "Monday": fmt.Println("Start of the week") case "Friday": fmt.Println("Almost weekend!") case "Saturday", "Sunday": fmt.Println("Weekend!") default: fmt.Println("Midweek") } // Type switch var i interface{} = "hello" switch v := i.(type) { case string: fmt.Printf("String: %s\n", v) case int: fmt.Printf("Integer: %d\n", v) default: fmt.Printf("Unknown type\n") } }

Constants and Iota

Example:

package main import "fmt" const ( // Iota starts at 0 and increments Sunday = iota Monday Tuesday Wednesday Thursday Friday Saturday ) const ( // Using iota for bit flags Read = 1 << iota // 1 << 0 = 1 Write // 1 << 1 = 2 Execute // 1 << 2 = 4 ) const Pi = 3.14159 func main() { fmt.Println("Days:") fmt.Println("Sunday:", Sunday) fmt.Println("Monday:", Monday) fmt.Println("Saturday:", Saturday) fmt.Println("\nPermissions:") fmt.Println("Read:", Read) fmt.Println("Write:", Write) fmt.Println("Execute:", Execute) // Combined permissions permissions := Read | Write fmt.Printf("Read+Write: %d\n", permissions) fmt.Println("\nConstants:") fmt.Println("Pi:", Pi) fmt.Println("True:", true) fmt.Println("False:", false) fmt.Println("Nil:", nil) }