Go Basics
Types, goroutines, channels, interfaces, error handling, stdlib patterns.
golanguagebackend
# Go Basics
## Philosophy
- Explicit over implicit. Errors as values. Simple concurrency.
## Types & declarations
```go
var x int = 10
y := "hello" // short decl (function scope)
const Pi = 3.14159
type User struct {
ID int
Email string
age int // unexported
}
u := User{ID: 1, Email: "a@b.c"}
```
## Error handling
```go
func Divide(a, b float64) (float64, error) {
if b == 0 { return 0, fmt.Errorf("divide by zero") }
return a / b, nil
}
// Wrapping (Go 1.13+)
return 0, fmt.Errorf("calc: %w", err)
errors.Is(err, ErrNotFound)
errors.As(err, &myErr)
```
## Interfaces (implicit)
```go
type Writer interface { Write([]byte) (int, error) }
type File struct{}
func (f File) Write(b []byte) (int, error) { ... }
var w Writer = File{} // works -- no 'implements'
```
## Goroutines & channels
```go
go func() { doWork() }()
ch := make(chan int, 10) // buffered
ch <- 42
v := <-ch
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(i Item) { defer wg.Done(); process(i) }(item)
}
wg.Wait()
```
## Context
```go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
```
## HTTP server
```go
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
})
log.Fatal(http.ListenAndServe(":8080", nil))
```API: /api/skills/golang-basics