Go Syntax:

This tutorial covers all major Go syntax elements with example code blocks and tools to copy/download them.

Hello World
go
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
Variable Declaration
go
var name string = "Alice"
age := 25
If-Else Statement
go
if age > 18 {
    fmt.Println("Adult")
} else {
    fmt.Println("Minor")
}
Function Definition
go
func add(a int, b int) int {
    return a + b
}
Struct and Method
go
type Person struct {
    Name string
    Age  int
}

func (p Person) greet() {
    fmt.Println("Hello,", p.Name)
}
Goroutine and Channel
go
ch := make(chan int)
go func() {
    ch <- 42
}()
val := <-ch
fmt.Println(val)
Error Handling
go
f, err := os.Open("file.txt")
if err != nil {
    log.Fatal(err)
}
Interfaces
go
type Speaker interface {
    Speak()
}

type Dog struct {}

func (d Dog) Speak() {
    fmt.Println("Woof!")
}
Modules and Packages
go
go mod init example.com/mymodule

import (
    "fmt"
    "example.com/mymodule/mypackage"
)
Testing
go
import "testing"

func TestAdd(t *testing.T) {
    result := add(2, 3)
    if result != 5 {
        t.Errorf("Expected 5, got %d", result)
    }
}
Loops
go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
Maps
go
m := map[string]int{
    "a": 1,
    "b": 2,
}
fmt.Println(m["a"])
Slices
go
s := []int{1, 2, 3}
s = append(s, 4)
fmt.Println(s)
Defer, Panic, Recover
go
func mayPanic() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic")
        }
    }()
    panic("Something went wrong")
}