Communitygithub.com

JantonioFC/skillsbank

Go言語向けの慣用的で効率的なコードガイドライン。

skillsbank とは?

このスキルは、Go言語の開発者が慣用的で効率的なコードを書くための包括的なガイドラインを提供します。エラーハンドリング、スライスとマップの操作、ゴルーチンとチャネルの使用方法、構造体とインターフェースの設計、関数とクロージャのベストプラクティス、そしてGoに特有のアンチパターンについて、具体的なコード例とともに解説しています。各セクションでは、非推奨のパターンと推奨されるパターンを比較し、なぜそのパターンが優れているのかを明確に示しています。例えば、エラーハンドリングでは`%w`を使用したエラーラッピングの重要性、スライスでは既知のサイズに対する事前割り当て、ゴルーチンでは`errgroup`や`WaitGroup`によるライフサイクル管理などが強調されています。このガイドラインは主にClaude CodeやCursorのようなAIエージェントや、Goのコードレビューを行う開発者にとって有用です。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Go: 慣用的で効率的なリファレンス

目次

  1. エラーハンドリング
  2. スライスとマップ
  3. ゴルーチンとチャネル
  4. 構造体とインターフェース
  5. 関数とクロージャ
  6. Go特有のアンチパターン

1. エラーハンドリング {#errors}

// ❌ エラーを無視する
result, _ := os.Open(path)

// ✅ — 常にハンドリングする。エラーが明らかに無関係な場合のみ _ を使用
result, err := os.Open(path)
if err != nil {
    return fmt.Errorf("open %s: %w", path, err)
}
// ❌ 冗長なエラー変数
var err エラー
err := doA()
if err != nil { return err }
err = doB()
if err != nil { return err }

// ✅ — それぞれの :=/: は問題ない。これが慣用的なGo。"修正"しようとしないこと。
// 簡略化できること: if の本体が単一のreturn文である場合、1行にまとめる
if err := doA(); err != nil { return err }
if err := doB(); err != nil { return err }
// ❌ 付加価値のないカスタムエラー型
type MyError struct{ msg string }
func (e MyError) Error() string { return e.msg }

// ✅ — 呼び出し側が型を検査する必要がない限り、errors.New または fmt.Errorf を使用
var ErrNotFound = errors.New("not found")
return fmt.Errorf("lookup %q: %w", key, ErrNotFound)

エラーを %w(%v ではない)でラップし、呼び出し側が errors.Is / errors.As を使用できるようにする。


2. スライスとマップ {#slices}

// ❌ サイズが既知の場合でも、事前割り当てなしでスライスを成長させる
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)
}
// ❌ マップへの書き込み前に手動で存在確認を行う
if _, ok := m[key]; !ok {
    m[key] = []string{}
}
m[key] = append(m[key], value)

// ✅ — nilスライスへのappendは有効なGoのコード
m[key] = append(m[key], value)
// ❌ 代入によるマップのコピー(参照をコピーするだけ)
copy := original

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

3. ゴルーチンとチャネル {#concurrency}

// ❌ ライフサイクル管理なしのファイアアンドフォーゲットゴルーチン
go doWork()

// ✅ — errgroup または WaitGroup を使用して完了を追跡
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    doWork()
}()
wg.Wait()
// ❌ バッファなしチャネルが不必要なゴルーチンブロックを引き起こす
ch := make(chan Result)
go func() { ch <- compute() }()
result := <-ch

// ✅ — 単一の結果の場合、バッファ付きチャネルを使用して、受信側が早期に終了した場合のゴルーチンリークを回避
ch := make(chan Result, 1)
go func() { ch <- compute() }()
result := <-ch
// ❌ ビジーウェイトのデフォルトケースを持つselect
for {
    select {
    case v := <-ch:
        process(v)
    default:
        // スピン
    }
}

// ✅ — 本当に非ブロッキングが必要な場合を除き、ブロッキングselect
for v := range ch {
    process(v)
}

エラー収集を伴うファンアウトには golang.org/x/sync/errgroup を使用する。


4. 構造体とインターフェース {#structs}

// ❌ 巨大なインターフェース
type Storage interface {
    Get(key string) ([]byte, error)
    Set(key string, val []byte) error
    Delete(key string) error
    List(prefix string) ([]string, error)
    // ... さらに10個のメソッド
}

// ✅ — 小さく、合成可能なインターフェース
type Getter interface { Get(key string) ([]byte, error) }
type Setter interface { Set(key string, val []byte) error }
type Storage interface { Getter; Setter }
// ❌ コンストラクタから具象構造体を返す(呼び出し側を実装に縛る)
func NewStore() *RedisStore { ... }

// ✅ — 複数の実装がある、または想定される場合はインターフェースを返す
func NewStore() Storage { return &RedisStore{...} }
// ❌ 小さな値型に対するポインタレシーバ
func (p *Point) X() float64 { return p.x }

// ✅ — 小さな不変型には値レシーバ
func (p Point) X() float64 { return p.x }

ルール: メソッドが状態を変更する場合、または構造体が大きい場合(3フィールド以上で、かつ重要なサイズ)はポインタレシーバ。それ以外は値レシーバ。


5. 関数とクロージャ {#functions}

// ❌ 単なる変数宣言の回避のために名前付き戻り値を使用
func divide(a, b float64) (result float64, err error) {
    result = a / b
    return
}

// ✅ — 名前付き戻り値は、遅延ミューテーションやドキュメンテーションの場合にのみ価値がある
func divide(a, b float64) (float64, error) {
    if b == 0 { return 0, errors.New("division by zero") }
    return a / b, nil
}
// ❌ ループ変数をキャプチャするクロージャ(古典的なGoのバグ。Go 1.22+ で修正)
// 1.22未満: 各ゴルーチンが同じ i をキャプチャする
for i := 0; i < n; i++ {
    go func() { use(i) }()
}

// ✅ (Go <1.22 — パラメータとして渡す)
for i := 0; i < n; i++ {
    go func(i int) { use(i) }(i)
}
// Go 1.22+: ループ変数は各イテレーションでスコープされるため、元のコードは安全

6. Go特有のアンチパターン {#antipatterns}

アンチパターン推奨パターン
if err != nil { return err } を5回以上繰り返す許容範囲 — 慣用的なGoである
予期されるエラーに対する panicreturn err
副作用のある init()main またはコンストラクタでの明示的な初期化
ジェネリクスなしの interface{} / anyジェネリクス(Go 1.18+)または型付きインターフェースを使用
保護するデータの隣にないMutexフィールドmu を保護するフィールドの真上に配置
チャネルのチャネル通常は設計過剰の兆候。再設計する
テスト内の time.Sleep同期のために testing フックまたはチャネルを使用
エクスポートされていないフィールドを持つエクスポートされた型(フィールドが全てを決める場合)全フィールドがエクスポートされた record スタイルの構造体
main 以外での log.Fatalスタックの上位にエラーを返す

制限事項

  • これらは言語固有のガイドラインであり、全体的なアーキテクチャ上の決定をカバーするものではありません。
  • 過度な圧縮は可読性を低下させる可能性があるため、判断を適用してください。

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.

関連スキル