Go: Simplicity and Performance
Learn Go, Google language for scalable systems and concurrency
1 Loading...
Go: Simplicity and Performance
Go (or Golang) is a programming language created by Google in 2009. Designed by Rob Pike, Ken Thompson, and Robert Griesemer, Go combines the efficiency of compiled languages with the ease of use of dynamic languages. It’s especially popular for building web services, command-line tools, and distributed systems.
Why Go? Go is used by companies like Google, Uber, Dropbox, Docker, and Kubernetes. Its simplicity and excellent concurrency support make it ideal for microservices and cloud-native systems.
Distinctive Features
- Fast Compilation - Compile large projects in seconds
- Garbage Collection - Efficient automatic memory management
- Native Concurrency - Goroutines and channels make parallel programming easy
- Static Typing - With type inference for concise code
- Integrated Tools - Native formatting, testing, and build tools
- Single Binary - Compile to a single executable without dependencies
Fundamentals
Data Types and Variables
package main
import "fmt"
func main() {
// Explicit declaration
var name string = "Maria"
var age int = 25
var height float64 = 1.68
var active bool = true
// Short declaration (type inference)
email := "[email protected]"
counter := 0
// Constants
const pi = 3.14159
const (
StatusPending = iota // 0
StatusApproved // 1
StatusRejected // 2
)
// Arrays (fixed size)
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
// Slices (dynamic size)
fruits := []string{"apple", "banana", "orange"}
fruits = append(fruits, "grape")
// Maps
users := map[string]int{
"alice": 25,
"bob": 30,
}
users["carol"] = 28
fmt.Println(name, age, height, active, email)
fmt.Println(numbers, fruits, users)
}
Control Structures
package main
import "fmt"
func main() {
// If/else
age := 18
if age >= 18 {
fmt.Println("Adult")
} else if age >= 13 {
fmt.Println("Teenager")
} else {
fmt.Println("Child")
}
// If with initial statement
if value := getValue(); value > 0 {
fmt.Println("Positive value:", value)
}
// For (only loop in Go)
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// For as while
counter := 0
for counter < 10 {
counter++
}
// For range
fruits := []string{"apple", "banana", "orange"}
for index, fruit := range fruits {
fmt.Printf("%d: %s\n", index, fruit)
}
// Switch
day := "monday"
switch day {
case "monday", "tuesday", "wednesday", "thursday", "friday":
fmt.Println("Weekday")
case "saturday", "sunday":
fmt.Println("Weekend")
default:
fmt.Println("Invalid day")
}
}
func getValue() int {
return 42
}
Functions
package main
import (
"errors"
"fmt"
)
// Simple function
func greet(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
// Multiple returns
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named returns
func calculate(a, b int) (sum, product int) {
sum = a + b
product = a * b
return // implicit return
}
// Variadic function
func sum(numbers ...int) int {
total := 0
for _, n := range numbers {
total += n
}
return total
}
// Closure
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
fmt.Println(greet("Maria"))
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
fmt.Println(sum(1, 2, 3, 4, 5))
cnt := counter()
fmt.Println(cnt(), cnt(), cnt())
}
Structs and Methods
package main
import "fmt"
// Struct
type User struct {
ID int
Name string
Email string
Active bool
}
// Method (value receiver)
func (u User) Greet() string {
return fmt.Sprintf("Hello, %s!", u.Name)
}
// Method (pointer receiver - can modify)
func (u *User) Deactivate() {
u.Active = false
}
// Constructor (convention)
func NewUser(id int, name, email string) *User {
return &User{
ID: id,
Name: name,
Email: email,
Active: true,
}
}
// Embedding (composition)
type Admin struct {
User // Embedded
Permissions []string
}
func main() {
u1 := User{ID: 1, Name: "Maria", Email: "[email protected]", Active: true}
u2 := NewUser(2, "John", "[email protected]")
fmt.Println(u1.Greet())
fmt.Println(u2.Greet())
u2.Deactivate()
fmt.Println("John active:", u2.Active)
admin := Admin{
User: User{ID: 3, Name: "Carlos", Active: true},
Permissions: []string{"create", "edit", "delete"},
}
fmt.Println(admin.Greet()) // Inherited method
}
Interfaces
package main
import (
"fmt"
"math"
)
// Interface
type Shape interface {
Area() float64
Perimeter() float64
}
// Implementation: Rectangle
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)
}
// Implementation: Circle
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
}
// Function accepting interface
func describeShape(s Shape) {
fmt.Printf("Area: %.2f, Perimeter: %.2f\n", s.Area(), s.Perimeter())
}
func main() {
rect := Rectangle{Width: 10, Height: 5}
circ := Circle{Radius: 7}
describeShape(rect)
describeShape(circ)
}
Concurrency
package main
import (
"fmt"
"sync"
"time"
)
// Basic goroutine
func task(id int) {
for i := 0; i < 3; i++ {
fmt.Printf("Task %d: iteration %d\n", id, i)
time.Sleep(100 * time.Millisecond)
}
}
// Channels
func producer(ch chan<- int) {
for i := 0; i < 5; i++ {
ch <- i
time.Sleep(100 * time.Millisecond)
}
close(ch)
}
func consumer(ch <-chan int) {
for value := range ch {
fmt.Println("Received:", value)
}
}
// WaitGroup
func withWaitGroup() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Worker %d executing\n", id)
time.Sleep(time.Second)
}(i)
}
wg.Wait()
fmt.Println("All workers finished")
}
func main() {
// Goroutines
go task(1)
go task(2)
time.Sleep(500 * time.Millisecond)
// Channels
ch := make(chan int)
go producer(ch)
consumer(ch)
// WaitGroup
withWaitGroup()
}
Essential Tools
| Command | Purpose |
|---|---|
go build | Compiles the project |
go run | Compiles and executes |
go test | Runs tests |
go fmt | Formats code |
go mod init | Initializes module |
go get | Adds dependency |
Learning Checklist
- Master basic types and data structures
- Understand functions, methods, and interfaces
- Learn goroutines and channels
- Study concurrency patterns
- Practice with REST APIs
- Explore native testing
- Build a microservice
Essential Resources
Quote
“Go is designed for people who write and maintain large software systems.” - Rob Pike
Go is the perfect choice when you need performance, simplicity, and excellent concurrency support!