Skip to content

GO

Hello World program

package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}

Variables and constants

var x int = 10
y := 20
const Pi float64 = 3.14159

Functions

func add(x, y int) int {
    return x + y
}

Loops

for i := 0; i < 10; i++ {
    fmt.Println(i)
}

Conditional statements

if x > y {
    fmt.Println("x is greater than y")
} else if x < y {
    fmt.Println("x is less than y")
} else {
    fmt.Println("x is equal to y")
}

Arrays and slices

var a [5]int
b := []int{1, 2, 3, 4, 5}
c := make([]int, 5)

Maps

var m map[string]int
m = make(map[string]int)
m["one"] = 1
m["two"] = 2

Pointers

var p *int
i := 10
p = &i
fmt.Println(*p)

Structs

type Person struct {
    Name string
    Age  int
}
p := Person{Name: "John", Age: 30}

Interfaces

type Shape interface {
    area() float64
}
type Rectangle struct {
    width  float64
    height float64
}
func (r Rectangle) area() float64 {
    return r.width * r.height
}

Goroutines and channels

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "processing job", j)
        results <- j * 2
    }
}
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 3; w++ {
    go worker(w, jobs, results)
}
for j := 1; j <= 5; j++ {
    jobs <- j
}
close(jobs)
for a := 1; a <= 5; a++ {
    <-results
}