Communitygithub.com

Go: Idiomatische Effizienzreferenz

Sprachspezifische Super-Code-Richtlinien für Go.

Was ist Go: Idiomatische Effizienzreferenz?

Dieses Skill bietet eine umfassende Sammlung von Go-Idiomen und Anti-Patterns, die Entwicklern helfen, sauberen, effizienten und wartbaren Go-Code zu schreiben. Es deckt die wichtigsten Bereiche wie Fehlerbehandlung, Slices & Maps, Goroutines & Channels, Structs & Interfaces sowie Funktionen & Closures ab. Jeder Abschnitt enthält klare Beispiele mit unerwünschten und bevorzugten Ansätzen, einschließlich prägnanter Erklärungen. Das Skill unterstützt die gängigsten Go-Entwicklungsumgebungen, die Skills unterstützen, und ist als Markdown-Dokumentation strukturiert, die direkt in den Entwicklungsablauf integriert werden kann. Die Richtlinien basieren auf den offiziellen Go-Konventionen und Best Practices aus der Community, mit besonderem Fokus auf Idiomatik und Leistung.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/skills/go

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Go: Idiomatische Effizienzreferenz?

Inhaltsverzeichnis

  1. Fehlerbehandlung
  2. Slices & Maps
  3. Goroutines & Channels
  4. Structs & Interfaces
  5. Funktionen & Closures
  6. Anti-Patterns spezifisch für Go

1. Fehlerbehandlung {#fehler}

// ❌ Fehler ignorieren
result, _ := os.Open(path)

// ✅ — immer behandeln; _ nur verwenden, wenn der Fehler nachweislich irrelevant ist
result, err := os.Open(path)
if err != nil {
    return fmt.Errorf("open %s: %w", path, err)
}
// ❌ Redundante Fehlervariable
err := doA()
if err != nil { return err }
err = doB()
if err != nil { return err }

// ✅ — jedes :=/: ist in Ordnung; das ist idiomatisches Go. Versuche nicht, es zu "verbessern".
// Was DU vereinfachen kannst: Zusammenfassen zu Einzeilern, wenn der if-Body ein einzelnes return ist
if err := doA(); err != nil { return err }
if err := doB(); err != nil { return err }
// ❌ Benutzerdefinierter Fehlertyp ohne Mehrwert
type MyError struct{ msg string }
func (e MyError) Error() string { return e.msg }

// ✅ — errors.New oder fmt.Errorf verwenden, es sei denn, Aufrufer müssen den Typ inspizieren
var ErrNotFound = errors.New("not found")
return fmt.Errorf("lookup %q: %w", key, ErrNotFound)

Fehler mit %w (nicht %v) verpacken, damit Aufrufer errors.Is / errors.As verwenden können.


2. Slices & Maps {#slices}

// ❌ Wachsen eines Slice ohne Vorabzuweisung, wenn die Größe bekannt ist
var result []string
for _, item := range items {
    result = append(result, item.Name)
}

// ✅
result := make([]string, 0, len(items))
for _, item := range items {
    result = append(result, item.Name)
}
// ❌ Manuelle Existenzprüfung vor Map-Schreibzugriff
if _, ok := m[key]; !ok {
    m[key] = []string{}
}
m[key] = append(m[key], value)

// ✅ — Anhängen an nil-Slice ist gültiges Go
m[key] = append(m[key], value)
// ❌ Kopieren einer Map durch Zuweisung (kopiert Referenz)
copy := original

// ✅
copy := make(map[K]V, len(original))
for k, v := range original { copy[k] = v }

3. Goroutines & Channels {#concurrency}

// ❌ Feuer-und-Vergessen-Goroutine ohne Lebenszyklus
go doWork()

// ✅ — errgroup oder WaitGroup verwenden, um die Fertigstellung zu verfolgen
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    doWork()
}()
wg.Wait()
// ❌ Ungepufferter Channel verursacht unnötigen Goroutine-Block
ch := make(chan Result)
go func() { ch <- compute() }()
result := <-ch

// ✅ — für Einzelergebnisse vermeidet gepufferter Channel Goroutine-Leaks, wenn der Empfänger vorzeitig beendet
ch := make(chan Result, 1)
go func() { ch <- compute() }()
result := <-ch
// ❌ select mit busy-wait default
for {
    select {
    case v := <-ch:
        process(v)
    default:
        // spin
    }
}

// ✅ — blockierendes select, es sei denn, du benötigst wirklich nicht-blockierendes Verhalten
for v := range ch {
    process(v)
}

Verwende golang.org/x/sync/errgroup für Fan-Out mit Fehlersammlung.


4. Structs & Interfaces {#structs}

// ❌ Großes Interface
type Storage interface {
    Get(key string) ([]byte, error)
    Set(key string, val []byte) error
    Delete(key string) error
    List(prefix string) ([]string, error)
    // ... 10 weitere Methoden
}

// ✅ — kleine, zusammensetzbare Interfaces
type Getter interface { Get(key string) ([]byte, error) }
type Setter interface { Set(key string, val []byte) error }
type Storage interface { Getter; Setter }
// ❌ Konkreten Struct aus Konstruktor zurückgeben (bindet Aufrufer an Implementierung)
func NewStore() *RedisStore { ... }

// ✅ — Interface zurückgeben, wenn es mehrere Implementierungen gibt oder zu erwarten sind
func NewStore() Storage { return &RedisStore{...} }
// ❌ Pointer-Empfänger für kleine Werttypen
func (p *Point) X() float64 { return p.x }

// ✅ — Wert-Empfänger für kleine unveränderliche Typen
func (p Point) X() float64 { return p.x }

Regel: Pointer-Empfänger, wenn die Methode den Zustand ändert ODER der Struct groß ist (>3 Felder von nicht-trivialer Größe). Sonst Wert-Empfänger.


5. Funktionen & Closures {#funktionen}

// ❌ Benannte Rückgabewerte nur verwendet, um eine Variablendeklaration zu vermeiden
func divide(a, b float64) (result float64, err error) {
    result = a / b
    return
}

// ✅ — benannte Rückgaben lohnen sich nur für verzögerte Mutation oder Dokumentation
func divide(a, b float64) (float64, error) {
    if b == 0 { return 0, errors.New("division by zero") }
    return a / b, nil
}
// ❌ Closure fängt Schleifenvariable ein (klassischer Go-Bug, behoben in Go 1.22+)
// Vor 1.22: Jede Goroutine fängt dasselbe i ein
for i := 0; i < n; i++ {
    go func() { use(i) }()
}

// ✅ (Go <1.22 — als Parameter übergeben)
for i := 0; i < n; i++ {
    go func(i int) { use(i) }(i)
}
// Go 1.22+: Schleifenvariable ist pro Iteration gültig, daher ist das Original sicher

6. Anti-Patterns spezifisch für Go {#antipatterns}

Anti-PatternBevorzugt
if err != nil { return err } 5+ mal wiederholtakzeptabel — es ist idiomatisches Go
panic für erwartete Fehlerreturn err
init() mit Seiteneffektenexplizite Initialisierung in main oder Konstruktoren
interface{} / any ohne GenericsGenerics (Go 1.18+) oder typisierte Interfaces verwenden
Mutex-Feld nicht neben den Daten, die es schütztmu direkt über dem Feld platzieren, das es bewacht
Channel von Channelsmeist ein Zeichen von Over-Engineering; umgestalten
time.Sleep in Teststesting-Hooks oder Channels zur Synchronisation verwenden
Exportierte Typen mit unexportierten Feldern (wenn die Felder der ganze Sinn sind)record-artige Structs mit ausschließlich exportierten Feldern
log.Fatal außerhalb von mainFehler nach oben zurückgeben

Einschränkungen

  • Dies sind sprachspezifische Richtlinien und decken keine allgemeinen Architekturentscheidungen ab.
  • Übermäßige Verdichtung kann die Lesbarkeit beeinträchtigen; mit Bedacht anwenden.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

JantonioFC/skillsbank

AI-powered image editing with style transfer and object removal

JantonioFC/skillsbank

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

JantonioFC/skillsbank

Analise e auditoria de editais de leilao judicial e extrajudicial. Riscos ocultos, clausulas perigosas, debitos, ocupante e classificacao da oportunidade.

JantonioFC/skillsbank

Embed Photopea in web apps using photopea.js. Covers embedding, file I/O, scripting, exporting, layers, text, filters, and the full Photoshop-compatible API.

JantonioFC/skillsbank

Best practices for Remotion - Video creation in React

JantonioFC/skillsbank

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

JantonioFC/skillsbank

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

JantonioFC/skillsbank

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

JantonioFC/skillsbank

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

JantonioFC/skillsbank

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

JantonioFC/skillsbank

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

JantonioFC/skillsbank

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

JantonioFC/skillsbank

Tool lifecycle UI components for React/Next.js from ui.inference.sh. Display tool calls: pending, progress, approval required, results. Capabilities: tool status, progress indicators, approval flows, results display. Use for: showing agent tool calls, human-in-the-loop approvals, tool output. Triggers: tool ui, tool calls, tool status, tool approval, tool results, agent tools, mcp tools ui, function calling ui, tool lifecycle, tool pending

JantonioFC/skillsbank

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

JantonioFC/skillsbank

When the user wants help with paid advertising campaigns on Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X, or other ad platforms. Also use when the user mentions 'PPC,' 'paid media,' 'ROAS,' 'CPA,' 'ad campaign,' 'retargeting,' 'audience targeting,' 'Google Ads,' 'Facebook ads,'...

JantonioFC/skillsbank

Create AI avatar and talking head videos with OmniHuman, Fabric, PixVerse via inference.sh CLI. Models: OmniHuman 1.5, OmniHuman 1.0, Fabric 1.0, PixVerse Lipsync. Capabilities: audio-driven avatars, lipsync videos, talking head generation, virtual presenters. Use for: AI presenters, expla...

JantonioFC/skillsbank

Create AI marketing videos for ads, promos, product launches, and brand content. Models: Veo, Seedance, Wan, FLUX for visuals, Kokoro for voiceover. Types: product demos, testimonials, explainers, social ads, brand videos. Use for: Facebook ads, YouTube ads, product launches, brand awarene...

JantonioFC/skillsbank

Generate AI videos with Google Veo, Seedance, Wan, Grok and 40+ models via inference.sh CLI. Models: Veo 3.1, Veo 3, Seedance 1.5 Pro, Wan 2.5, Grok Imagine Video, OmniHuman, Fabric, HunyuanVideo. Capabilities: text-to-video, image-to-video, lipsync, avatar animation, video upscaling, fole...

JantonioFC/skillsbank

Production-ready CI/CD configurations for Playwright — GitHub Actions, GitLab CI, CircleCI, Azure DevOps, Jenkins, Docker, parallel sharding, reporting, code coverage, and global setup/teardown.

JantonioFC/skillsbank

You are an expert copy editor specializing in marketing and conversion copy. Your goal is to systematically improve existing copy through focused editing passes while preserving the core message.

Verwandte Skills