Dasar
Hello World
package main import "fmt" func main() { fmt.Println("Hello, World!") }
Jalankan & Build
go run main.go # compile and run go build -o app . # compile to binary go test ./... # run all tests
Inisialisasi Module
go mod init github.com/user/project go mod tidy # sync dependencies
Variabel & Tipe
Deklarasi
var name string = "Go" age := 15 // short declaration var x, y int = 1, 2 const Pi = 3.14159
Tipe Dasar
booltrue, false
stringUrutan byte UTF-8 immutable
int, int8..int64Integer bertanda (platform / lebar tetap)
uint, uint8..uint64Integer tak bertanda
float32, float64Bilangan pecahan IEEE-754
byteAlias untuk uint8
runeAlias untuk int32 (Unicode code point)
Nilai Zero
int, float0
boolfalse
string"" (string kosong)
pointer, slice, mapnil
Fungsi
Fungsi Dasar
func add(a, b int) int { return a + b }
Beberapa Nilai Kembalian
func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil }
Variadic & Anonim
func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total } double := func(x int) int { return x * 2 }
Defer
func readFile(path string) { f, _ := os.Open(path) defer f.Close() // runs when function returns }
Alur Kontrol
If / Else
if x > 0 { fmt.Println("positive") } else if x == 0 { fmt.Println("zero") } else { fmt.Println("negative") }
Perulangan For
for i := 0; i < 10; i++ { } // classic for x < 100 { x *= 2 } // while-style for { break } // infinite for i, v := range slice { } // range
Switch
switch day { case "Mon", "Tue": fmt.Println("early week") case "Fri": fmt.Println("TGIF") default: fmt.Println("other") }
Struct & Method
Definisi Struct
type User struct { Name string Email string Age int } u := User{Name: "Alice", Email: "[email protected]", Age: 30}
Method
func (u User) Greeting() string { return "Hi, " + u.Name } func (u *User) SetAge(age int) { u.Age = age // pointer receiver mutates }
Embedding
type Admin struct { User // embedded struct Level string } a := Admin{User: User{Name: "Bob"}, Level: "super"} fmt.Println(a.Name) // promoted field
Interface
Definisi & Implementasi
type Stringer interface { String() string } // implicit implementation — no "implements" keyword func (u User) String() string { return u.Name }
Interface Umum
io.ReaderRead(p []byte) (n int, err error)
io.WriterWrite(p []byte) (n int, err error)
fmt.StringerString() string
errorError() string
Type Assertion
var i interface{} = "hello" s, ok := i.(string) // ok == true switch v := i.(type) { case string: fmt.Println(v) case int: fmt.Println(v * 2) }
Goroutine & Channel
Goroutine
go func() { fmt.Println("running concurrently") }() time.Sleep(time.Second)
Channel
ch := make(chan int) // unbuffered buf := make(chan int, 5) // buffered ch <- 42 // send val := <-ch // receive
Select
select { case msg := <-ch1: fmt.Println(msg) case ch2 <- 42: fmt.Println("sent") case <-time.After(time.Second): fmt.Println("timeout") }
Pola Umum
sync.WaitGroupMenunggu beberapa goroutine selesai
sync.MutexLock mutual exclusion untuk shared state
context.ContextPembatalan, deadline, nilai request-scoped
Penanganan Error
Pola Dasar
result, err := doSomething() if err != nil { return fmt.Errorf("failed: %w", err) }
Custom Error
type NotFoundError struct { ID string } func (e *NotFoundError) Error() string { return "not found: " + e.ID }
Package errors
errors.New(msg)Buat error sederhana
fmt.Errorf("%w", err)Bungkus error dengan konteks
errors.Is(err, target)Periksa rantai error untuk kecocokan
errors.As(err, &target)Ekstrak typed error dari rantai
Slice & Map
Slice
s := []int{1, 2, 3} s = append(s, 4, 5) sub := s[1:3] // [2, 3] cp := make([]int, len(s)) copy(cp, s)
Map
m := map[string]int{"a": 1, "b": 2} m["c"] = 3 val, ok := m["a"] // ok == true delete(m, "b") for k, v := range m { }
Operasi Slice
len(s)Jumlah elemen
cap(s)Kapasitas array dasar
append(s, elems...)Tambah elemen, mungkin realokasi
copy(dst, src)Salin elemen antar slice
slices.Sort(s)Urutkan slice (Go 1.21+ package slices)
Package & Import
Gaya Import
import "fmt" import ( "os" "strings" "github.com/user/pkg" )
Visibilitas
Huruf kapital di awal = exported (public). Huruf kecil di awal = unexported (package-private). Tidak perlu keyword seperti public/private.
Standard Library Umum
fmtI/O terformat (Print, Sprintf, Errorf)
osFungsi OS (file, env, args)
ioPrimitif I/O (Reader, Writer)
net/httpHTTP client dan server
encoding/jsonEncode/decode JSON
stringsFungsi manipulasi string
strconvKonversi string ↔ angka
testingFramework unit test
Generics
Parameter Tipe
func Map[T, U any](s []T, f func(T) U) []U { r := make([]U, len(s)) for i, v := range s { r[i] = f(v) } return r }
Constraint
type Number interface { ~int | ~float64 } func Sum[T Number](nums []T) T { var total T for _, n := range nums { total += n } return total }
Testing
Test Dasar
// file: math_test.go func TestAdd(t *testing.T) { got := Add(2, 3) if got != 5 { t.Errorf("Add(2,3) = %d, want 5", got) } }
Perintah Test
go testJalankan test di package saat ini
go test ./...Jalankan semua test secara rekursif
go test -vOutput verbose
go test -run TestAddJalankan test tertentu berdasarkan nama
go test -bench .Jalankan benchmark
go test -coverTampilkan persentase coverage