一键导入
use-modern-go
Apply modern Go syntax guidelines based on project's Go version. Use when user ask for modern Go code guidelines.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Apply modern Go syntax guidelines based on project's Go version. Use when user ask for modern Go code guidelines.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
Context usage patterns for Go including cancellation, timeouts, deadlines, and database transactions. Use when handling HTTP requests, database operations, or implementing cancellation and timeout logic.
Error handling patterns for Go including error wrapping, custom errors, sentinel errors, and error checking best practices. Use when implementing error handling, defining error types, or working with error flows.
Modern Go testing patterns including table-driven tests, subtests, test organization, and best practices. Use when writing or refactoring tests, implementing test coverage, or when the user asks about Go testing approaches.
Prefer typed constants and named types over magic strings/numbers in Go. Use when writing function signatures, struct fields, switch statements, or passing enum-like values.
Behavioral guidelines to reduce common LLM coding mistakes by emphasizing thinking before coding, simplicity, surgical changes, and goal-driven execution. Use when implementing features, fixing bugs, refactoring code, or performing any coding task.
基于 SOC 职业分类
| name | use-modern-go |
| description | Apply modern Go syntax guidelines based on project's Go version. Use when user ask for modern Go code guidelines. |
!grep -rh "^go " --include="go.mod" . 2>/dev/null | cut -d' ' -f2 | sort | uniq -c | sort -nr | head -1 | xargs | cut -d' ' -f2 | grep . || echo unknown
DO NOT search for go.mod files or try to detect the version yourself. Use ONLY the version shown above.
If version detected (not "unknown"):
If version is "unknown":
When writing Go code, use ALL features from this document up to the target version:
slices, maps, cmp) over legacy patternstime.Since: time.Since(start) instead of time.Now().Sub(start)time.Until: time.Until(deadline) instead of deadline.Sub(time.Now())errors.Is: errors.Is(err, target) instead of err == target (works with wrapped errors)any: Use any instead of interface{}bytes.Cut: before, after, found := bytes.Cut(b, sep) instead of Index+slicestrings.Cut: before, after, found := strings.Cut(s, sep)fmt.Appendf: buf = fmt.Appendf(buf, "x=%d", x) instead of []byte(fmt.Sprintf(...))atomic.Bool/atomic.Int64/atomic.Pointer[T]: Type-safe atomics instead of atomic.StoreInt32var flag atomic.Bool
flag.Store(true)
if flag.Load() { ... }
var ptr atomic.Pointer[Config]
ptr.Store(cfg)
strings.Clone: strings.Clone(s) to copy string without sharing memorybytes.Clone: bytes.Clone(b) to copy byte slicestrings.CutPrefix/CutSuffix: if rest, ok := strings.CutPrefix(s, "pre:"); ok { ... }errors.Join: errors.Join(err1, err2) to combine multiple errorscontext.WithCancelCause: ctx, cancel := context.WithCancelCause(parent) then cancel(err)context.Cause: context.Cause(ctx) to get the error that caused cancellationBuilt-ins:
min/max: max(a, b) instead of if/else comparisonsclear: clear(m) to delete all map entries, clear(s) to zero slice elementsslices package:
slices.Contains: slices.Contains(items, x) instead of manual loopsslices.Index: slices.Index(items, x) returns index (-1 if not found)slices.IndexFunc: slices.IndexFunc(items, func(item T) bool { return item.ID == id })slices.SortFunc: slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })slices.Sort: slices.Sort(items) for ordered typesslices.Max/slices.Min: slices.Max(items) instead of manual loopslices.Reverse: slices.Reverse(items) instead of manual swap loopslices.Compact: slices.Compact(items) removes consecutive duplicates in-placeslices.Clip: slices.Clip(s) removes unused capacityslices.Clone: slices.Clone(s) creates a copymaps package:
maps.Clone: maps.Clone(m) instead of manual map iterationmaps.Copy: maps.Copy(dst, src) copies entries from src to dstmaps.DeleteFunc: maps.DeleteFunc(m, func(k K, v V) bool { return condition })sync package:
sync.OnceFunc: f := sync.OnceFunc(func() { ... }) instead of sync.Once + wrappersync.OnceValue: getter := sync.OnceValue(func() T { return computeValue() })context package:
context.AfterFunc: stop := context.AfterFunc(ctx, cleanup) runs cleanup on cancellationcontext.WithTimeoutCause: ctx, cancel := context.WithTimeoutCause(parent, d, err)context.WithDeadlineCause: Similar with deadline instead of durationLoops:
for i := range n: for i := range len(items) instead of for i := 0; i < len(items); i++cmp package:
cmp.Or: cmp.Or(flag, env, config, "default") returns first non-zero value// Instead of:
name := os.Getenv("NAME")
if name == "" {
name = "default"
}
// Use:
name := cmp.Or(os.Getenv("NAME"), "default")
reflect package:
reflect.TypeFor: reflect.TypeFor[T]() instead of reflect.TypeOf((*T)(nil)).Elem()net/http:
http.ServeMux patterns: mux.HandleFunc("GET /api/{id}", handler) with method and path paramsr.PathValue("id") to get path parametersmaps.Keys(m) / maps.Values(m) return iteratorsslices.Collect(iter) not manual loop to build slice from iteratorslices.Sorted(iter) to collect and sort in one stepkeys := slices.Collect(maps.Keys(m)) // not: for k := range m { keys = append(keys, k) }
sortedKeys := slices.Sorted(maps.Keys(m)) // collect + sort
for k := range maps.Keys(m) { process(k) } // iterate directly
time package
time.Tick: Use time.Tick freely — as of Go 1.23, the garbage collector can recover unreferenced tickers, even if they haven't been stopped. The Stop method is no longer necessary to help the garbage collector. There is no longer any reason to prefer NewTicker when Tick will do.t.Context(): ALWAYS use t.Context() when a test function needs a context.func TestFoo(t *testing.T) {
ctx := t.Context()
result := doSomething(ctx)
}
omitzero: ALWAYS use omitzero (not omitempty) for time.Duration, time.Time, structs, slices, maps.type Config struct {
Timeout time.Duration `json:"timeout,omitzero"`
}
b.Loop(): ALWAYS use b.Loop() for the main loop in benchmark functions.func BenchmarkFoo(b *testing.B) {
for b.Loop() {
doWork()
}
}
strings.SplitSeq / strings.FieldsSeq: ALWAYS use when iterating split results in a for-range loop.
Also: bytes.SplitSeq, bytes.FieldsSeq.for part := range strings.SplitSeq(s, ",") {
process(part)
}
wg.Go(fn): ALWAYS use wg.Go() when spawning goroutines with sync.WaitGroup.var wg sync.WaitGroup
for _, item := range items {
wg.Go(func() {
process(item)
})
}
wg.Wait()
These features are NOT available in the current project. Do not use them until the go.mod version is upgraded to 1.26+.
new(val) — new() extended to accept expressions, not just types. Returns pointer to any value.
new(0) → *int, new("s") → *string, new(T{}) → *T.cfg := Config{
Timeout: new(30), // *int
Debug: new(true), // *bool
}
errors.AsType[T](err) — generic alternative to errors.As(err, &target).if pathErr, ok := errors.AsType[*os.PathError](err); ok {
handle(pathErr)
}