Логотип Zig

Zig

Сообщество
rudedogg
zig

Up-to-date Zig programming language patterns for version 0.15.x. Use when writing, reviewing, or debugging Zig code, working with build.zig and build.zig.zon files, or using comptime metaprogramming. Critical for avoiding outdated patterns from training data - especially build system APIs (root_module instead of root_source_file), I/O APIs (buffered writer pattern), container initialization (.empty/.init), allocator selection (DebugAllocator), and removed language features (async/await, usingnamespace).

Обзор

Издательrudedogg
Репозиторийzig-skills
Название навыкаzig
Звёзды
37
Форки
11
Встроенные файлы
55
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 55

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Опубликовано на GitHub: rudedogg. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Zig в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/rudedogg/zig-skills/tree/main/zig
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/rudedogg/zig-skills.git /tmp/zig-skills
mkdir -p .claude/skills
cp -r /tmp/zig-skills/zig .claude/skills/zig
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Zig в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Zig, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Zig не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Zig Language Reference (v0.15.2)

Zig evolves rapidly. Training data contains outdated patterns that cause compilation errors. This skill documents breaking changes and correct modern patterns.

Critical: Removed Features (0.15.x)

usingnamespace - REMOVED

zig
// WRONG - compile error
pub usingnamespace @import("other.zig");

// CORRECT - explicit re-export
const other = @import("other.zig");
pub const foo = other.foo;

async/await - REMOVED

Keywords removed from language. Async I/O support is planned for future releases.

Critical: I/O API Rewrite ("Writergate")

The entire std.io API changed. New std.Io.Writer and std.Io.Reader are non-generic with buffer in the interface.

Writing

zig
// WRONG - old API
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello\n", .{});

// CORRECT - new API: provide buffer, access .interface, flush
var buf: [4096]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&buf);
const stdout = &stdout_writer.interface;
try stdout.print("Hello\n", .{});
try stdout.flush();  // REQUIRED!

Reading

zig
// Reading from file
var buf: [4096]u8 = undefined;
var file_reader = file.reader(&buf);
const r = &file_reader.interface;

// Read line by line (takeDelimiter returns null at EOF)
while (try r.takeDelimiter('\n')) |line| {
    // process line (doesn't include '\n')
}

// Read binary data
const header = try r.takeStruct(Header, .little);
const value = try r.takeInt(u32, .big);

Fixed Buffer Writer (no file)

zig
var buf: [256]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try w.print("Hello {s}", .{"world"});
const result = w.buffered();  // "Hello world"

Fixed Reader (from slice)

zig
var r: std.Io.Reader = .fixed("hello\nworld");
const line = (try r.takeDelimiter('\n')).?;  // "hello" (returns null at EOF)

Deprecated: BufferedWriter, CountingWriter, std.io.bufferedWriter()

Deprecated: GenericWriter, GenericReader, AnyWriter, AnyReader, FixedBufferStream

New: std.Io.Writer, std.Io.Reader - non-generic, buffer in interface

Replacements:

  • CountingWriter → std.Io.Writer.Discarding (has .fullCount())
  • BufferedWriter → buffer provided to .writer(&buf) call
  • Allocating output → std.Io.Writer.Allocating

Critical: Build System (0.15.x)

root_source_file is REMOVED from addExecutable/addLibrary/addTest. Use root_module:

zig
// WRONG - removed field
b.addExecutable(.{
    .name = "app",
    .root_source_file = b.path("src/main.zig"),  // ERROR
    .target = target,
});

// CORRECT
b.addExecutable(.{
    .name = "app",
    .root_module = b.createModule(.{
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    }),
});

Module imports changed:

zig
// WRONG (old API)
exe.addModule("helper", helper_mod);

// CORRECT
exe.root_module.addImport("helper", helper_mod);

Adding dependency modules:

zig
const dep = b.dependency("lib", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("lib", dep.module("lib"));

Compile-level methods deprecated: exe.linkSystemLibrary(), exe.addCSourceFiles(), exe.addIncludePath(), exe.linkLibC() are deprecated — use exe.root_module.* equivalents instead.

See std.Build reference for complete build system documentation.

Critical: Container Initialization

Never use .{} for containers. Use .empty or .init:

zig
// WRONG - deprecated
var list: std.ArrayList(u32) = .{};
var gpa: std.heap.DebugAllocator(.{}) = .{};

// CORRECT - use .empty for empty collections
var list: std.ArrayList(u32) = .empty;
var map: std.AutoHashMapUnmanaged(u32, u32) = .empty;

// CORRECT - use .init for stateful types with internal config
var gpa: std.heap.DebugAllocator(.{}) = .init;
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);

Naming Changes

  • std.ArrayListUnmanaged → std.ArrayList (Unmanaged is now default, old name deprecated)
  • std.heap.GeneralPurposeAllocator → std.heap.DebugAllocator (GPA alias still works)

std.BoundedArray - REMOVED. Use:

zig
var buffer: [8]i32 = undefined;
var stack = std.ArrayList(i32).initBuffer(&buffer);

Critical: Format Strings (0.15.x)

{f} required to call format methods:

zig
// WRONG - ambiguous error
std.debug.print("{}", .{std.zig.fmtId("x")});

// CORRECT
std.debug.print("{f}", .{std.zig.fmtId("x")});

Format method signature changed:

zig
// OLD - wrong
pub fn format(self: @This(), comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void

// NEW - correct
pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void

Breaking Changes (0.14.0+)

@branchHint replaces @setCold

zig
// WRONG
@setCold(true);

// CORRECT
@branchHint(.cold);  // Must be first statement in block

@export takes pointer

zig
// WRONG
@export(foo, .{ .name = "bar" });

// CORRECT
@export(&foo, .{ .name = "bar" });

Inline asm clobbers are typed

zig
// WRONG
: "rcx", "r11"

// CORRECT
: .{ .rcx = true, .r11 = true }

@fence - REMOVED

Use stronger atomic orderings or RMW operations instead.

Decl Literals (0.14.0+)

.identifier syntax works for declarations:

zig
const S = struct {
    x: u32,
    const default: S = .{ .x = 0 };
    fn init(v: u32) S { return .{ .x = v }; }
};

const a: S = .default;      // S.default
const b: S = .init(42);     // S.init(42)
const c: S = try .init(1);  // works with try

Labeled Switch (0.14.0+)

State machines use continue :label:

zig
state: switch (initial) {
    .idle => continue :state .running,
    .running => if (done) break :state result else continue :state .running,
    .error => return error.Failed,
}

Non-exhaustive Enum Switch (0.15.x)

Can mix explicit tags with _ and else:

zig
switch (value) {
    .a, .b => {},
    else => {},  // other named tags
    _ => {},     // unnamed integer values
}

Quick Fixes

ErrorFix
no field 'root_source_file'Use root_module = b.createModule(.{...})
use of undefined valueArithmetic on undefined is now illegal
type 'f32' cannot represent integerUse float literal: 123_456_789.0 not 123_456_789
ambiguous format stringUse {f} for format methods
sanitize_c = trueType changed to ?std.zig.SanitizeC — use .full, .trap, or .off
std.fifo.LinearFifoRemoved — use std.Io.Reader/Writer patterns
posix.sendfileRemoved — use std.fs.File writer .sendFileAll()
std.fmt.FormatterDeprecated — renamed to std.fmt.Alt
fmtSliceEscapeLower/UpperUse std.ascii.hexEscape(bytes, .lower/.upper)

Language References

Load these references when working with core language features:

Code Style

  • Style Guide - Official Zig naming conventions (TitleCase types, camelCase functions, snake_case variables), whitespace rules, doc comment guidance, redundancy avoidance, zig fmt

Language Basics & Built-ins

  • Language Basics - Core language: types, control flow (if/while/for/switch), error handling (try/catch/errdefer), optionals, structs, enums, unions, pointers, slices, comptime, functions
  • Built-in Functions - All @ built-ins: type casts (@intCast, @bitCast, @ptrCast), arithmetic (@addWithOverflow, @divExact), bit ops (@clz, @popCount), memory (@memcpy, @sizeOf), atomics (@atomicRmw, @cmpxchgWeak), introspection (@typeInfo, @TypeOf, @hasDecl), SIMD (@Vector, @splat, @reduce), C interop (@cImport, @export)

Standard Library References

Load these references when working with specific modules:

Memory & Slices

  • std.mem - Slice search/compare, split/tokenize, alignment, endianness, byte conversion

Text & Encoding

  • std.fmt - Format strings, integer/float parsing, hex encoding, custom formatters, {f} specifier (0.15.x)
  • std.ascii - ASCII character classification (isAlpha, isDigit), case conversion, case-insensitive comparison
  • std.unicode - UTF-8/UTF-16 encoding/decoding, codepoint iteration, validation, WTF-8 for Windows
  • std.base64 - Base64 encoding/decoding (standard, URL-safe, with/without padding)

Math & Random

  • std.math - Floating-point ops, trig, overflow-checked arithmetic, constants, complex numbers, big integers
  • std.Random - PRNGs (Xoshiro256, Pcg), CSPRNGs (ChaCha), random integers/floats/booleans, shuffle, distributions
  • std.hash - Non-cryptographic hash functions (Wyhash, XxHash, FNV, Murmur, CityHash), checksums (CRC32, Adler32), auto-hashing

SIMD & Vectorization

  • std.simd - SIMD vector utilities: optimal vector length, iota/repeat/join/interlace patterns, element shifting/rotation, parallel searching, prefix scans, branchless selection

Time & Timing

  • std.time - Wall-clock timestamps, monotonic Instant/Timer, epoch conversions, calendar utilities (year/month/day), time unit constants
  • std.Tz - TZif timezone database parsing (RFC 8536), UTC offsets, DST rules, timezone abbreviations, leap seconds

Sorting & Searching

  • std.sort - Sorting algorithms (pdq, block, heap, insertion), binary search, min/max

Core Data Structures

Allocators

  • std.heap - Allocator selection guide, ArenaAllocator, DebugAllocator, FixedBufferAllocator, MemoryPool, SmpAllocator, ThreadSafeAllocator, StackFallbackAllocator, custom allocator implementation

I/O & Files

  • std.io - Reader/Writer API (0.15.x): buffered I/O, streaming, binary data, format strings
  • std.fs - File system: files, directories, iteration, atomic writes, paths
  • std.tar - Tar archive reading/writing, extraction, POSIX ustar, GNU/pax extensions
  • std.zip - ZIP archive reading/extraction, ZIP64 support, store/deflate compression
  • std.compress - Compression: DEFLATE (gzip, zlib), Zstandard, LZMA, LZMA2, XZ decompression/compression

Networking

  • std.http - HTTP client/server, TLS, connection pooling, compression, WebSocket
  • std.net - TCP/UDP sockets, address parsing, DNS resolution
  • std.Uri - URI parsing/formatting (RFC 3986), percent-encoding/decoding, relative URI resolution

Process Management

  • std.process - Child process spawning, environment variables, argument parsing, exec

OS-Specific APIs

  • std.os - OS-specific APIs: Linux syscalls, io_uring, Windows NT APIs, WASI, direct platform access
  • std.c - C ABI types and libc bindings: platform-specific types (fd_t, pid_t, timespec), errno values, socket/signal/memory types, fcntl/open flags, FFI with C libraries

Concurrency

  • std.Thread - Thread spawning, Mutex, RwLock, Condition, Semaphore, WaitGroup, thread pools
  • std.atomic - Lock-free atomic operations: Value wrapper, fetch-and-modify (add/sub/and/or/xor), compare-and-swap, atomic ordering semantics, spin loop hints, cache line sizing

Patterns & Best Practices

  • Zig Patterns - Load when writing new code or reviewing code quality. Comprehensive best practices extracted from the Zig standard library: quick patterns (memory/allocators, file I/O, HTTP, JSON, testing, build system) plus idiomatic code patterns covering syntax (closures, context pattern, options structs, destructuring), polymorphism (duck typing, generics, custom formatting, dynamic/static dispatch), safety (diagnostics, error payloads, defer/errdefer, compile-time assertions), and performance (const pointer passing)
  • Code Review - Load when reviewing Zig code. Systematic checklist organized by confidence level: ALWAYS FLAG (removed features, changed syntax, API changes), FLAG WITH CONTEXT (exception safety bugs, missing flush, allocator issues), SUGGEST (style improvements). Includes migration examples for 0.14/0.15 breaking changes

Serialization

  • std.json - JSON parsing, serialization, dynamic values, streaming, custom parse/stringify
  • std.zon - ZON (Zig Object Notation) parsing and serialization for build.zig.zon, config files, data interchange

Testing & Debug

  • std.testing - Unit test assertions and utilities
  • std.debug - Panic, assert, stack traces, hex dump, format specifiers
  • std.log - Scoped logging with configurable levels and output

Metaprogramming

  • Comptime Reference - Comptime fundamentals, type reflection (@typeInfo/@Type/@TypeOf), loop variants (comptime for vs inline for), branch elimination, type generation, comptime limitations
  • std.meta - Type introspection, field iteration, stringToEnum, generic programming

Compiler Utilities

  • std.zig - AST parsing, tokenization, source analysis, linters, formatters, ZON parsing

Security & Cryptography

  • std.crypto - Hashing (SHA2, SHA3, Blake3), AEAD (AES-GCM, ChaCha20-Poly1305), signatures (Ed25519, ECDSA), key exchange (X25519), password hashing (Argon2, scrypt, bcrypt), secure random, timing-safe operations

Build System

  • std.Build - Build system: build.zig, modules, dependencies, build.zig.zon, steps, options, testing, C/C++ integration

Interoperability

  • C Interop - Exporting C-compatible APIs: export fn, C calling convention, building static/dynamic libraries, creating headers, macOS universal binaries, XCFramework for Swift/Xcode, module maps

Встроенные файлы

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Zig?

Up-to-date Zig programming language patterns for version 0.15.x. Use when writing, reviewing, or debugging Zig code, working with build.zig and build.zig.zon files, or using comptime metaprogramming. Critical for avoiding outdated patterns from training data - especially build system APIs (root_module instead of root_source_file), I/O APIs (buffered writer pattern), container initialization (.empty/.init), allocator selection (DebugAllocator), and removed language features (async/await, usingnamespace).

Зачем использовать Zig в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Zig — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Zig в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/rudedogg/zig-skills/tree/main/zig. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Zig?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Zig?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Zig: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Zig?

Навык опубликован на GitHub автором rudedogg. Условия лицензии можно найти в репозитории. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇