Go Overview
Go is an open-source programming language developed at Google that makes it easy to build simple, reliable, and efficient software. It combines the development speed of dynamic languages with the performance and safety of compiled languages.
Key Features
- Simplicity: Clean syntax with minimal keywords.
- Concurrency: Goroutines and channels make concurrency easy.
- Fast Compilation: Compiles quickly to machine code.
- Garbage Collection: Automatic memory management.
- Static Typing: Type safety with type inference.
- Standard Library: Comprehensive standard library.
- Cross-Platform: Compiles to many platforms.
Common Use Cases
Cloud Services
Used by Docker, Kubernetes, and cloud infrastructure.
Web Servers
High-performance HTTP servers and APIs.
DevOps Tools
Command-line tools and utilities.
Networking
Network applications and services.
Example Code
// Go example demonstrating concurrency and features
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
// Struct type
type Person struct {
Name string
Age int
}
// Method
func (p Person) Greet() string {
return fmt.Sprintf("Hello, my name is %s", p.Name)
}
// Interface
type Greeter interface {
Greet() string
}
func main() {
// Variables and struct
person := Person{"Alice", 30}
fmt.Println(person.Greet())
// Slice and map
numbers := []int{1, 2, 3, 4, 5}
squares := make(map[int]int)
for _, n := range numbers {
squares[n] = n * n
}
fmt.Println(squares)
// Goroutines and WaitGroup
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
time.Sleep(time.Second)
fmt.Printf("Goroutine %d done\n", id)
}(i)
}
wg.Wait()
// HTTP server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
})
fmt.Println("Server starting on :8080")
http.ListenAndServe(":8080", nil)
}