zig-comptime
БесплатноБез исполняемых скриптовНе проверенZig comptime skill for compile-time evaluation and metaprogramming. Use when using comptime parameters, comptime types, generics via anytype, comptime…
от mohitmishra786★ 307 звёзд на GitHubОб этом скилле
Zig comptime
Purpose
Guide agents through Zig's comptime system: compile-time function evaluation, comptime type parameters, generics via anytype, type reflection with @typeInfo, and metaprogramming patterns that replace C++ templates and macros.
Triggers
- "How does comptime work in Zig?"
- "How do I write a generic function in Zig?"
- "How do I use @typeInfo for reflection?"
- "How do I generate code at compile time in Zig?"
- "How does anytype work in Zig?"
- "How do Zig generics compare to C++ templates?"
Workflow
1. comptime basics
// comptime keyword forces compile-time evaluation
const x: comptime_int = 42; // comptime integer (arbitrary precision)
const y: comptime_float = 3.14159; // comptime float (arbitrary precision)
// comptime block — runs at compile time
comptime {
const val = fibonacci(20); // computed at compile time
std.debug.assert(val == 6765); // compile-time assertion
}
// comptime parameter — caller must provide a comptime-known value
fn makeArray(comptime T: type, comptime n: usize) [n]T {
return [_]T{0} ** n; // array of n zeros of type T
}
const arr = makeArray(f32, 8); // [8]f32 computed at compile time
2. Generic functions with comptime type parameters
const std = @import("std");
// Generic max function — T must be comptime-known
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
// Usage: T is inferred from arguments or specified explicitly
const r1 = max(i32, 3, 7); // 7
const r2 = max(f64, 2.5, 1.8); // 2.5
// Generic Stack data structure
fn Stack(comptime T: type) type {
return struct {
items: []T,
top: usize,
allocator: std.mem.Allocator,
const Self = @This();
pub fn init(allocator: std.mem.Allocator) !Self {
return Self{
.items = try allocator.alloc(T, 64),
.top = 0,
.allocator = allocator,
};
}
pub fn push(self: *Self, value: T) void {
self.items[self.top] = value;
self.top += 1;
}
pub fn pop(self: *Self) ?T {
if (self.top == 0) return null;
self.top -= 1;
return self.items[self.top];
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.items);
}
};
}
// Usage: Stack(i32) and Stack(f64) are distinct types
var int_stack = try Stack(i32).init(allocator);
defer int_stack.deinit();
int_stack.push(42);
3. anytype — duck-typed comptime parameters
anytype accepts any type and the compiler infers it at the call site:
// anytype: function works for any type with .len field
fn printLength(thing: anytype) void {
std.debug.print("Length: {}\n", .{thing.len});
}
printLength("hello"); // string literal — works
printLength([_]u8{1, 2, 3}); // array — works
printLength(list.items); // slice (e.g. ArrayList items) — works
// printLength(list) is a compile error: ArrayList has no .len field
// anytype with comptime checks for better errors
fn serialize(writer: anytype, value: anytype) !void {
// Verify writer has write method at comptime
if (!@hasDecl(@TypeOf(writer), "write")) {
@compileError("writer must have a write method");
}
try writer.write(std.mem.asBytes(&value));
}
// Custom formatting: since 0.15 format takes a *std.Io.Writer (no anytype writer)
pub fn format(self: MyType, writer: *std.Io.Writer) std.Io.Writer.Error!void {
try writer.print("{d} {d}", .{ self.x, self.y });
}
// Use with the {f} specifier: std.debug.print("{f}\n", .{my_value});
4. Type reflection with @typeInfo
@typeInfo returns a tagged union describing a type's structure at comptime:
const std = @import("std");
const TypeInfo = std.builtin.Type;
// @typeInfo tags are lowercase since 0.14; keywords need @"..." (.@"struct", .@"enum")
fn printTypeInfo(comptime T: type) void {
switch (@typeInfo(T)) {
.int => |i| std.debug.print("Int: {d} bits, {t}\n", .{ i.bits, i.signedness }),
.float => |f| std.debug.print("Float: {d} bits\n", .{f.bits}),
.@"struct" => |s| {
std.debug.print("Struct with {d} fields:\n", .{s.fields.len});
inline for (s.fields) |field| {
std.debug.print(" {s}: {s}\n", .{ field.name, @typeName(field.type) });
}
},
.@"enum" => |e| {
std.debug.print("Enum with {d} values:\n", .{e.fields.len});
inline for (e.fields) |field| {
std.debug.print(" {s} = {d}\n", .{ field.name, field.value });
}
},
.optional => |o| std.debug.print("Optional({s})\n", .{@typeName(o.child)}),
.array => |a| std.debug.print("[{d}]{s}\n", .{ a.len, @typeName(a.child) }),
else => std.debug.print("Other type: {s}\n", .{@typeName(T)}),
}
}
// The swit
Установить zig-comptime в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл zig-comptime?
Zig comptime skill for compile-time evaluation and metaprogramming. Use when using comptime parameters, comptime types, generics via anytype, comptime reflection with @typeInfo, or metaprogramming patterns that replace C++ templates. Activates on queries about Zig comptime, compile-time evaluation, Zig generics, anytype, @typeInfo, comptime types, or Zig metaprogramming.
Как установить скилл zig-comptime?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zig-comptime запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic