Logo vun Go Control Structures

Go Control Structures

Communautéit
v0lka
go-control-structures

Enforces correct usage of Go control structures including range loops, break statements, and defer in loops. Use when writing or reviewing Go code that iterates over slices, arrays, maps, or channels with range, uses break inside switch/select within loops, or places defer calls inside loops.

Iwwersiicht

Editeurv0lka
Repositoryskills
Skill-Nummgo-control-structures
Stären
28
Forks
1
Matgeliwwert Fichieren
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum v0lka op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Go Control Structures an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-control-structures
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/v0lka/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/development/idiomatic-go/go-control-structures .claude/skills/go-control-structures
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Go Control Structures an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Go Control Structures automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Go Control Structures net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Go Control Structures

Rules for avoiding common mistakes with range loops, break statements, and defer in Go.

Range Loops Copy the Value Variable

The value variable in a range loop is a copy of the element. Mutating it does not modify the original collection.

Wrong -- mutates only the copy:

go
for _, a := range accounts {
    a.balance += 1000 // has no effect on the slice
}

Correct -- access via index:

go
for i := range accounts {
    accounts[i].balance += 1000
}

Rules:

  • When you need to mutate struct elements in a slice/array, use the index variable (for i := range), not the value variable.
  • If the slice already holds pointers ([]*T), mutation through the value variable works, but be aware of CPU cache implications for large collections.
  • Read-only iteration with the value variable is fine.

Range Expression Is Evaluated Once

The expression passed to range is copied once before the loop starts. The loop iterates over this snapshot.

Slices

Appending to a slice during range does not extend the iteration -- the loop uses the original length:

go
s := []int{0, 1, 2}
for range s {
    s = append(s, 10) // loop still runs exactly 3 times
}

A classic for i := 0; i < len(s); i++ re-evaluates len(s) each iteration and would loop forever with the same append logic.

Channels

Reassigning the channel variable inside the loop body has no effect -- range iterates over the channel captured at the start:

go
ch := ch1
for v := range ch {
    ch = ch2 // has no effect; range still reads from ch1
}

Arrays

range copies the entire array (not just a slice header). Modifications to the original array are not visible through the value variable:

go
a := [3]int{0, 1, 2}
for i, v := range a {
    a[2] = 10
    if i == 2 {
        fmt.Println(v) // prints 2, not 10
    }
}

To see mutations, either:

  • Access the element via index: a[i]
  • Range over a pointer: for i, v := range &a { ... }

Ranging over &a avoids the full array copy -- prefer this for large arrays.

Pointer to Range Variable Trap

The range value variable has a single address across all iterations. Storing &v always stores the same pointer, which ends up pointing to the last element.

Wrong -- all map entries point to the last customer:

go
for _, customer := range customers {
    s.m[customer.ID] = &customer // same address every iteration
}

Fix 1 -- local copy:

go
for _, customer := range customers {
    current := customer
    s.m[current.ID] = &current
}

Fix 2 -- pointer via index:

go
for i := range customers {
    customer := &customers[i]
    s.m[customer.ID] = customer
}

Rules:

  • Never store &rangeValueVar across iterations. The agent must flag this pattern in reviews.
  • Apply the same caution with slices and maps alike.

Map Iteration Assumptions

No ordering guarantees

Maps in Go provide:

  • No sorting by key
  • No preservation of insertion order
  • No deterministic iteration order (order varies between runs)

Never write code that depends on map iteration order. If ordered traversal is needed, collect keys into a slice, sort it, and iterate over the sorted slice.

Inserting during iteration is non-deterministic

A new map entry added during iteration may or may not be visited in that same iteration. The behavior varies per entry and per run.

Wrong -- unpredictable results:

go
for k, v := range m {
    if v {
        m[10+k] = true // may or may not appear in this iteration
    }
}

Correct -- read from original, write to a copy:

go
m2 := copyMap(m)
for k, v := range m {
    m2[k] = v
    if v {
        m2[10+k] = true
    }
}

Rules:

  • Deleting map entries during iteration is safe (deleted keys will not appear later).
  • Inserting entries during iteration produces non-deterministic results. Separate the read map from the write map when adding entries.

Break Terminates the Innermost for/switch/select

break inside a switch or select that is inside a for loop breaks the switch/select, not the loop.

Wrong -- break exits switch, loop continues:

go
for i := 0; i < 5; i++ {
    switch i {
    case 2:
        break // breaks the switch, NOT the for loop
    }
}

Correct -- use a label:

go
loop:
    for i := 0; i < 5; i++ {
        switch i {
        case 2:
            break loop // breaks the for loop
        }
    }

Same pattern applies to select inside a loop:

go
loop:
    for {
        select {
        case <-ch:
            // handle
        case <-ctx.Done():
            break loop // breaks the for loop, not select
        }
    }

Rules:

  • Whenever break appears inside a switch or select nested in a loop, verify that the intent is to break the inner statement. If the intent is to exit the loop, require a labeled break.
  • continue with a label can similarly target an outer loop.
  • Labeled breaks are idiomatic Go (used in the standard library, e.g., net/http).

Defer Inside a Loop

defer executes when the surrounding function returns, not at the end of each loop iteration. Placing defer directly in a loop body defers all calls until the function exits, leaking resources for the loop's lifetime.

Wrong -- file descriptors stay open until readFiles returns:

go
func readFiles(ch <-chan string) error {
    for path := range ch {
        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close() // not called until readFiles returns
        // ...
    }
    return nil
}

Correct -- extract the body into a function so defer fires each iteration:

go
func readFiles(ch <-chan string) error {
    for path := range ch {
        if err := readFile(path); err != nil {
            return err
        }
    }
    return nil
}

func readFile(path string) error {
    file, err := os.Open(path)
    if err != nil {
        return err
    }
    defer file.Close()
    // ...
    return nil
}

An anonymous closure also works:

go
for path := range ch {
    if err := func() error {
        f, err := os.Open(path)
        if err != nil {
            return err
        }
        defer f.Close()
        // ...
        return nil
    }(); err != nil {
        return err
    }
}

Rules:

  • Flag any defer that appears directly inside a for/range loop body. Wrap the loop body in a helper function or closure so defer fires per iteration.
  • This applies to any resource cleanup (file handles, locks, DB connections, HTTP response bodies).

Heefeg gestallte Froen

Wat mécht de KI-Skill Go Control Structures?

Enforces correct usage of Go control structures including range loops, break statements, and defer in loops. Use when writing or reviewing Go code that iterates over slices, arrays, maps, or channels with range, uses break inside switch/select within loops, or places defer calls inside loops.

Firwat Go Control Structures op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Go Control Structures besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Go Control Structures an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-control-structures an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Go Control Structures benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Go Control Structures benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Go Control Structures domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Go Control Structures gratis?

Jo. De Skill gëtt vum v0lka ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇