Установка
SKILL.md
Modern Go Guidelines
Detected Go Version
!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
How to Use This Skill
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"):
- Say: "This project is using Go X.XX, so I’ll stick to modern Go best practices and freely use language features up to and including this version. If you’d prefer a different target version, just let me know."
- Do NOT list features, do NOT ask for confirmation
If version is "unknown":
- Say: "Could not detect Go version in this repository"
- Use AskUserQuestion: "Which Go version should I target?" → [1.23] / [1.24] / [1.25] / [1.26]
When writing Go code, use ALL features from this document up to the target version:
- Prefer modern built-ins and packages (
slices,maps,cmp) over legacy patterns - Never use features from newer Go versions than the target
- Never use outdated patterns when a modern alternative is available
Features by Go Version
Go 1.0+
time.Since:time.Since(start)instead oftime.Now().Sub(start)
Go 1.8+
time.Until:time.Until(deadline)instead ofdeadline.Sub(time.Now())
Go 1.13+
errors.Is:errors.Is(err, target)instead oferr == target(works with wrapped errors)
Go 1.18+
any: Useanyinstead ofinterface{}bytes.Cut:before, after, found := bytes.Cut(b, sep)instead of Index+slicestrings.Cut:before, after, found := strings.Cut(s, sep)
Go 1.19+
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 ofatomic.StoreInt32
var flag atomic.Bool
flag.Store(true)
if flag.Load() { ... }
var ptr atomic.Pointer[Config]
ptr.Store(cfg)
Go 1.20+
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)thencancel(err)context.Cause:context.Cause(ctx)to get the error that caused cancellation
Go 1.21+
Built-ins:
min/max:max(a, b)instead of if/else comparisonsclear:clear(m)to delete all map entries,clear(s)to zero slice elements
slices 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 copy
maps 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 ofsync.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 duration
Go 1.22+
Loops:
for i := range n:for i := range len(items)instead offor i := 0; i < len(items); i++- Loop variables are now safe to capture in goroutines (each iteration has its own copy)
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 ofreflect.TypeOf((*T)(nil)).Elem()
net/http:
- Enhanced
http.ServeMuxpatterns:mux.HandleFunc("GET /api/{id}", handler)with method and path params r.PathValue("id")to get path parameters
Go 1.23+
maps.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 step
keys := 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: Usetime.Tickfreely — 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.
Go 1.24+
t.Context()notcontext.WithCancel(context.Background())in tests. ALWAYS use t.Context() when a test function needs a context.
Before:
func TestFoo(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
result := doSomething(ctx)
}
After:
func TestFoo(t *testing.T) {
ctx := t.Context()
result := doSomething(ctx)
}
omitzeronotomitemptyin JSON struct tags. ALWAYS use omitzero for time.Duration, time.Time, structs, slices, maps.
Before:
type Config struct {
Timeout time.Duration `json:"timeout,omitempty"` // doesn't work for Duration!
}
After:
type Config struct {
Timeout time.Duration `json:"timeout,omitzero"`
}
b.Loop()notfor i := 0; i < b.N; i++in benchmarks. ALWAYS use b.Loop() for the main loop in benchmark functions.
Before:
func BenchmarkFoo(b *testing.B) {
for i := 0; i < b.N; i++ {
doWork()
}
}
After:
func BenchmarkFoo(b *testing.B) {
for b.Loop() {
doWork()
}
}
strings.SplitSeqnotstrings.Splitwhen iterating. ALWAYS use SplitSeq/FieldsSeq when iterating over split results in a for-range loop.
Before:
for _, part := range strings.Split(s, ",") {
process(part)
}
After:
for part := range strings.SplitSeq(s, ",") {
process(part)
}
Also: strings.FieldsSeq, bytes.SplitSeq, bytes.FieldsSeq.
Go 1.25+
wg.Go(fn)notwg.Add(1)+go func() { defer wg.Done(); ... }(). ALWAYS use wg.Go() when spawning goroutines with sync.WaitGroup.
Before:
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func() {
defer wg.Done()
process(item)
}()
}
wg.Wait()
After:
var wg sync.WaitGroup
for _, item := range items {
wg.Go(func() {
process(item)
})
}
wg.Wait()
Go 1.26+
new(val)notx := val; &x— returns pointer to any value. Go 1.26 extends new() to accept expressions, not just types. Type is inferred: new(0) → *int, new("s") → *string, new(T{}) → *T. DO NOT usex := val; &xpattern — always use new(val) directly. DO NOT use redundant casts like new(int(0)) — just write new(0). Common use case: struct fields with pointer types.
Before:
timeout := 30
debug := true
cfg := Config{
Timeout: &timeout,
Debug: &debug,
}
After:
cfg := Config{
Timeout: new(30), // *int
Debug: new(true), // *bool
}
errors.AsType[T](err)noterrors.As(err, &target). ALWAYS use errors.AsType when checking if error matches a specific type.
Before:
var pathErr *os.PathError
if errors.As(err, &pathErr) {
handle(pathErr)
}
After:
if pathErr, ok := errors.AsType[*os.PathError](err); ok {
handle(pathErr)
}
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: use-modern-go](https://darkplay.ru/ai/skills/jetbrains-go-modern-guidelines-use-modern-go)
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
Cpp Revieweraffaan-m · Ревьюер C++: безопасность памяти, современные идиомы, конкурентность, производительность.
aws-transformanthropics · Миграция, модернизация и обновление кодовых баз на AWS: .NET Framework в .NET 8/10, COBOL…
code-modernizationanthropics · Модернизация устаревших кодовых баз (COBOL, старые Java/C++, монолитные веб-приложения) с…
linearanthropics · Интеграция с трекером задач Linear: создание задач, управление проектами, обновление…
ui5-modernizationanthropics · Полный набор инструментов модернизации UI5 с рабочим процессом и специализированными…
javascript-typescriptwshobson · Разработка на JavaScript и TypeScript с ES6+, Node.js, React и современными…
julia-developmentwshobson · Современная разработка на Julia 1.10+, управление пакетами, научные вычисления…
python-developmentwshobson · Современная разработка на Python 3.12+, Django, FastAPI, асинхронные паттерны и лучшие…
ui-designwshobson · Комплексный плагин UI/UX-дизайна для мобильных (iOS, Android, React Native) и…
.NET Upgradegithub · Выполняет задачи по поддержке кода C#/.NET, включая очистку, модернизацию и устранение…Лучшие ИИ-инструменты для программирования
Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные
GenAPIGenapi
Notepad++ AINotepad-plus-plus
Creatium MaxCremax
Emacs AIGnu
KiteKite
Amazon Q DeveloperAmazonЛучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachat