# Referensi Cepat Go

*Sintaks, tipe, concurrency, penanganan error*

> Source: The Go Programming Language (go.dev) · MIT

## 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

| Command | Description |
|---------|-------------|
| `bool` | `true`, `false` |
| `string` | Urutan byte UTF-8 immutable |
| `int, int8..int64` | Integer bertanda (platform / lebar tetap) |
| `uint, uint8..uint64` | Integer tak bertanda |
| `float32, float64` | Bilangan pecahan IEEE-754 |
| `byte` | Alias untuk `uint8` |
| `rune` | Alias untuk `int32` (Unicode code point) |

### Nilai Zero

| Command | Description |
|---------|-------------|
| `int, float` | `0` |
| `bool` | `false` |
| `string` | `""` (string kosong) |
| `pointer, slice, map` | `nil` |

## 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: "a@b.com", 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

| Command | Description |
|---------|-------------|
| `io.Reader` | `Read(p []byte) (n int, err error)` |
| `io.Writer` | `Write(p []byte) (n int, err error)` |
| `fmt.Stringer` | `String() string` |
| `error` | `Error() 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

| Command | Description |
|---------|-------------|
| `sync.WaitGroup` | Menunggu beberapa goroutine selesai |
| `sync.Mutex` | Lock mutual exclusion untuk shared state |
| `context.Context` | Pembatalan, 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

| Command | Description |
|---------|-------------|
| `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

| Command | Description |
|---------|-------------|
| `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

| Command | Description |
|---------|-------------|
| `fmt` | I/O terformat (Print, Sprintf, Errorf) |
| `os` | Fungsi OS (file, env, args) |
| `io` | Primitif I/O (Reader, Writer) |
| `net/http` | HTTP client dan server |
| `encoding/json` | Encode/decode JSON |
| `strings` | Fungsi manipulasi string |
| `strconv` | Konversi string ↔ angka |
| `testing` | Framework 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

| Command | Description |
|---------|-------------|
| `go test` | Jalankan test di package saat ini |
| `go test ./...` | Jalankan semua test secara rekursif |
| `go test -v` | Output verbose |
| `go test -run TestAdd` | Jalankan test tertentu berdasarkan nama |
| `go test -bench .` | Jalankan benchmark |
| `go test -cover` | Tampilkan persentase coverage |
