golang-master
Golang language expert specializing in concurrency, performance optimization, standard library, and testing. Use when writing Go code, debugging concurrency issues, or optimizing performance.
What this skill does
# Golang Language Expert
Expert assistant for Go language mastery including concurrency patterns, performance optimization, standard library usage, and testing strategies.
## Thinking Process
When activated, follow this structured thinking approach to solve Go-related problems:
### Step 1: Problem Classification
**Goal:** Understand what type of Go challenge this is.
**Key Questions to Ask:**
- Is this a concurrency problem? (goroutines, channels, race conditions)
- Is this a performance problem? (memory, CPU, allocations)
- Is this a design problem? (interfaces, struct composition, packages)
- Is this a debugging problem? (error tracing, unexpected behavior)
- Is this a testing problem? (unit tests, benchmarks, mocks)
**Decision Point:** Classify the problem to select appropriate patterns:
- Concurrency → Check for race conditions, proper synchronization
- Performance → Profile first, then optimize
- Design → Apply interface segregation, composition over inheritance
- Debugging → Trace error chain, check nil handling
- Testing → Table-driven tests, dependency injection
### Step 2: Context Analysis
**Goal:** Understand the existing codebase context and constraints.
**Key Questions to Ask:**
- What Go version is being used? (generics require 1.18+)
- What is the module structure? (standard layout vs flat)
- What dependencies exist? (standard library vs third-party)
- Are there existing patterns to follow? (error handling style, logging approach)
**Actions:**
1. Check `go.mod` for Go version and dependencies
2. Scan existing code for established patterns
3. Identify any project-specific conventions
### Step 3: Solution Design (Idiomatic Go)
**Goal:** Design a solution that follows Go best practices.
**Thinking Framework - Apply These Principles:**
1. **Simplicity First**
- "Is there a simpler way to achieve this?"
- Avoid over-engineering; Go favors explicitness
2. **Error Handling**
- "What can fail here? How should failures propagate?"
- Use `fmt.Errorf("context: %w", err)` for wrapping
- Define custom error types for domain-specific errors
3. **Concurrency Safety**
- "Is this data accessed from multiple goroutines?"
- "Do I need a mutex, channel, or atomic operation?"
- Prefer channels for coordination, mutexes for state protection
4. **Interface Design**
- "What behavior is needed, not what data?"
- Keep interfaces small (1-3 methods)
- Accept interfaces, return concrete types
5. **Resource Management**
- "What needs to be closed/cleaned up?"
- Use defer for cleanup
- Propagate context for cancellation
### Step 4: Implementation with Patterns
**Goal:** Apply well-known Go patterns appropriately.
**Pattern Selection Guide:**
| Problem Type | Recommended Pattern |
|-------------|---------------------|
| Process N items concurrently | Worker Pool |
| Limit concurrent operations | Semaphore |
| Timeout long operations | Context with Deadline |
| Coordinate multiple goroutines | WaitGroup |
| Fan-out/Fan-in processing | Channel pipelines |
| Graceful shutdown | Context cancellation + signal handling |
**Decision Point:** For each pattern, ask:
- "Why is this pattern appropriate for this problem?"
- "What are the edge cases I need to handle?"
### Step 5: Testing Strategy
**Goal:** Ensure code correctness and maintainability.
**Thinking Framework:**
- "What are the happy paths to test?"
- "What edge cases could break this?"
- "Is this code testable? If not, how should I refactor?"
**Testing Checklist:**
1. Table-driven tests for functions with multiple input scenarios
2. Race detection for concurrent code (`go test -race`)
3. Benchmarks for performance-critical code
4. Mock interfaces for external dependencies
### Step 6: Review and Refine
**Goal:** Ensure the solution is production-ready.
**Final Checks:**
- [ ] All errors are handled or explicitly ignored with comment
- [ ] Context is propagated through the call chain
- [ ] Resources are properly closed (defer, Close())
- [ ] No goroutine leaks (channels closed, contexts cancelled)
- [ ] Code is testable (dependencies injected)
- [ ] Documentation for exported symbols
## Usage
### Run Linters
```bash
bash /mnt/skills/user/golang-master/scripts/lint.sh [project-dir] [fix-mode]
```
**Arguments:**
- `project-dir` - Project directory (default: current directory)
- `fix-mode` - Set to `true` to auto-fix issues (default: false)
**Examples:**
```bash
bash /mnt/skills/user/golang-master/scripts/lint.sh
bash /mnt/skills/user/golang-master/scripts/lint.sh ./my-project true
```
**Runs:** go vet, gofmt, staticcheck, golangci-lint, go mod tidy
### Run Benchmarks
```bash
bash /mnt/skills/user/golang-master/scripts/benchmark.sh [project-dir] [pattern] [profile-type]
```
**Arguments:**
- `project-dir` - Project directory (default: current directory)
- `pattern` - Benchmark pattern to match (default: .)
- `profile-type` - Profiling: none, cpu, mem, all (default: none)
**Examples:**
```bash
bash /mnt/skills/user/golang-master/scripts/benchmark.sh
bash /mnt/skills/user/golang-master/scripts/benchmark.sh . BenchmarkProcess cpu
bash /mnt/skills/user/golang-master/scripts/benchmark.sh ./myproject . all
```
## Documentation Resources
**Official Documentation:**
- Go Docs: `https://go.dev/doc/`
- Effective Go: `https://go.dev/doc/effective_go`
- Go by Example: `https://gobyexample.com/`
- uber-go/guide: `https://github.com/uber-go/guide`
## Concurrency Patterns
### Worker Pool
```go
func workerPool(jobs <-chan Job, numWorkers int) <-chan Result {
results := make(chan Result, len(jobs))
var wg sync.WaitGroup
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
results <- process(job)
}
}()
}
go func() {
wg.Wait()
close(results)
}()
return results
}
```
### Context with Timeout
```go
func fetchWithTimeout(url string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
```
### Semaphore Pattern
```go
type Semaphore struct {
sem chan struct{}
}
func NewSemaphore(n int) *Semaphore {
return &Semaphore{sem: make(chan struct{}, n)}
}
func (s *Semaphore) Acquire() { s.sem <- struct{}{} }
func (s *Semaphore) Release() { <-s.sem }
```
## Error Handling
### Wrapping Errors
```go
func processUser(id int) error {
user, err := fetchUser(id)
if err != nil {
return fmt.Errorf("failed to fetch user %d: %w", id, err)
}
if err := validateUser(user); err != nil {
return fmt.Errorf("validation failed for user %d: %w", id, err)
}
return nil
}
```
### Custom Error Types
```go
type NotFoundError struct {
Resource string
ID string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s not found: %s", e.Resource, e.ID)
}
// Usage
if errors.Is(err, &NotFoundError{}) {
// Handle not found
}
```
### Error Checking
```go
// Use errors.Is for sentinel errors
if errors.Is(err, sql.ErrNoRows) {
return nil, &NotFoundError{Resource: "user", ID: id}
}
// Use errors.As for error types
var netErr *net.OpError
if errors.As(err, &netErr) {
// Handle network error
}
```
## Performance Profiling
### CPU Profiling
```bash
# Run benchmark with CPU profile
go test -cpuprofile=cpu.prof -bench=.
go tool pprof cpu.prof
# Interactive commands
(pprof) top10
(pprof) web
(pprof) list FunctionName
```
### Memory Profiling
```bash
# Run benchmark with memory profile
go test -memprofile=mem.prof -bench=.
go tool pprof -alloc_space mem.prof
# Check for allocations
go build -gcflags='-m' ./Related in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.