~/saidqb cat ecosystem/programming-language/go.md
Go
Go
Compiled, statically typed language
commit by saidqb
Requirements
- Go
1.23.x(rilis 2x setahun, Feb & Agustus) — cek go.dev/dl
go version
Module & command
go mod init github.com/user/project
go get github.com/google/uuid
go mod tidy
go run main.go
go build -o app
go test ./...
go fmt ./...
go vet ./...
Variabel & tipe
var name string = "SaidQB"
age := 8 // type inference
const Pi = 3.14
var tags = []string{"go", "python", "php"}
config := map[string]bool{"debug": true}
Control flow
if age >= 18 { ... } else if age >= 13 { ... } else { ... }
for i := 0; i < 5; i++ { ... }
for _, tag := range tags { ... }
for { ... break } // infinite loop
switch status {
case "active": ...
case "inactive": ...
default: ...
}
Function, struct, method
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
type User struct {
Name string
Email string
}
func (u User) Greet() string { return "Halo, " + u.Name } // value receiver
func (u *User) SetName(n string) { u.Name = n } // pointer receiver
Interface
type Animal interface {
Sound() string
}
type Cat struct{}
func (c Cat) Sound() string { return "Meow" }
Goroutine & channel
ch := make(chan string)
go func() { ch <- "done" }()
msg := <-ch
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// kerjaan
}()
wg.Wait()
var mu sync.Mutex
mu.Lock(); defer mu.Unlock()
Error handling
if err != nil {
return fmt.Errorf("failed to fetch user: %w", err) // wrap error
}
errors.Is(err, sql.ErrNoRows)
errors.As(err, &myErr)