Visão geral da linguagem Zig

Zig 0.14 — linguagem de sistemas | nenhum fluxo de controle oculto | sem alocações ocultas | sem pré-processador | execução em tempo de compilação

Paradigma

Imperativo, processual, orientado a dados. Digitação estática com inferência, digitação estrutural (duck) via comptime. Compilação via LLVM + backend auto-hospedado. Sem sobrecarga de operador, sem exceções, sem RAII, sem macros.

Tipos

Categoria Tipos
Assinado i8 i16 i32 i64 i128 isize
Int não assinado u8 u16 u32 u64 u128 usize
Flutuar f16 f32 f64 f128
Bool bool
Vazio void
Nunca noreturn
Matriz [N]T
Fatia []T
Ponteiro *T *const T [*]T (muitos itens) [*c]T (ponteiro C)
Opcional ?T
União de erros E!T
Estrutura struct { field: T }
União union { field: T } (marcado)
Enum enum { variant }
Embalado union/enum packed union packed enum
Vetor @Vector(N, T) (SIMD)
Função fn(params) ReturnType
Opaco opaque {}
Comptime comptime T (tempo de compilação conhecido)
Qualquer tipo anytype (digitação de pato em tempo integral)
Qualquer erro anyerror
Tipo type (tipo de primeira classe)
Vazio (zero bits) comptime void

Declarações

Construir Sintaxe Notas
Função fn name(params) ReturnType { body }
Variável const x = expr; Imutável
Mutável var x = expr;
Constante const NAME: T = expr; Conhecido em Comptime
Exportar export fn name() void { ... } Visível para o vinculador
Externo extern fn name() void; De outro objeto
Estrutura const T = struct { field: T };
Enum const E = enum { variant };
União const U = union(enum) { field: T }; União marcada
Erro definido const Errors = error { E1, E2 };
Teste test "name" { ... }
Bloco Comptime comptime { ... }
Montagem embutida asm volatile ("code");
Importar const std = @import("std");

Fluxo de controle

Construir Sintaxe Notas
Se if (cond) { ... } else { ... }
Se (expressão) const x = if (cond) a else b;
Se (opcional) if (opt) |val| { ... } else { ... } Capturar desembrulhar
Se (união de erro) if (result) |val| { ... } else |err| { ... }
Enquanto while (cond) { ... }
Enquanto (opcional) while (opt) |val| { ... }
Enquanto (erro) while (result) |val| { ... } else |err| { ... }
Para for (slice) |item| { ... }
Para (índice) for (slice, 0..) |item, i| { ... }
Mudar switch (expr) { variant => body, else => body } Exaustivo
Pausa break;
Continuar continue;
Retorno return expr;
Adiar defer expr; Executar na saída do escopo
Errdefer errdefer expr; Executar em caso de erro
Pegar result catch |err| { ... } Desembrulhe ou manuseie

Alternar recursos

Operadores

Categoria Operadores
Aritmética + - * / %
Embrulho +% -% *%
Saturação +| -| *|
Comparação == != < > <= >=
Lógico and or !
Bit a bit >> << & | ^ ~
Composto += -= *= /%= &= |= ^= <<= >>=
Anulável orelse catch .? (desembrulhar opcional)
Diversos .. (intervalo) ** (ptr deref multi) . (campo) .* (ptr deref)
Endereço de &expr

Comptime (Metaprogramação)

fn max(comptime T: type, a: T, b: T) T {
    return if (a > b) a else b;
}

comptime {
    // Runs at compile time
    @compileLog("building for", @tagName(builtin.cpu));
}

// Generics via comptime parameters
fn ArrayList(comptime T: type) type {
    return struct {
        items: []T,
        fn init(self: *Self) void { ... }
    };
}

Recursos do Comptime

Memória

Operação Sintaxe Notas
Alocar allocator.alloc(T, n) Retorna ![]T
Grátis allocator.free(slice)
Reallocar allocator.realloc(slice, n)
Criar allocator.create(T) Elemento único
Destruir allocator.destroy(ptr)
Parâmetro do alocador allocator: Allocator Sempre explícito

Alocadores

std.heap.page_allocator std.heap.arena_allocator std.heap.FixedBufferAllocator std.heap.ArenaAllocator std.heap.StackFallbackAllocator std.heap.c_allocator

Filosofia do alocador de Zig

Tratamento de erros

// Error union type: ReturnType!Error
fn div(a: i32, b: i32) !i32 {
    if (b == 0) return error.DivisionByZero;
    return a / b;
}

// Try operator: early return on error
const result = try div(10, 2);

// Catch: provide default
const val = div(10, 0) catch 0;

// Global error set vs specific
fn parse() ParseError!i32 { ... }

Adiar e Errdefer

{
    const buf = try allocator.alloc(u8, 100);
    defer allocator.free(buf);  // always runs at scope exit
    errdefer allocator.free(buf);  // runs only if error returned

    // ... use buf
}  // defer triggers here

Biblioteca Padrão (selecionada)

Módulo Conteúdo
std.fs Arquivo, Dir, Caminho, cwd, readFile, writeFile, copyFile, deleteFile, makeDir, makePath
std.io Leitor, gravador, buffer, formatação, impressão
std.net TcpStream, TcpListener, UdpSocket, IpAddress, DNS
std.mem copiar, definir, trocar, indexOf, dividir, juntar, Allocator, interface Allocator
std.process ChildProcess, Args, Env, saída, getSelfPath
std.time Instantâneo, nanoTime, suspensão, temporizador, época
std.Thread spawn, Pool, Mutex, RwLock, Semáforo, Condição, Atômico
std.math sqrt, sin, cos, tan, exp, log, pow, abs, min, max, clamp
std.hash funções hash, crc32, sha256, sha512, md5
std.json analisar, stringificar, valor, matriz, objeto
std.sort classificar, pesquisa binária, inserção, mesclagem, pdqsort
std.unicode utf8, utf16, largura, mapeamento de caso
std.Build Sistema de compilação (substitui make/cmake)
std.Target Detecção de alvo de compilação cruzada
std.debug afirmar, entrar em pânico, imprimir, despejar, rastrear

Teste

test "basic addition" {
    try std.testing.expectEqual(4, add(2, 2));
    try std.testing.expect(add(1, 1) == 2);
    try std.testing.expectError(error.DivisionByZero, div(1, 0));
}
zig test file.zig        # run tests
zig build test           # run all tests in project
zig test --name "filter" # filter test names

Compilação Cruzada

zig build-exe main.zig --target x86_64-windows  # cross-compile to Windows
zig build-exe main.zig --target aarch64-linux    # cross-compile to ARM64 Linux
zig build-exe main.zig --target riscv64-linux    # cross-compile to RISC-V

O Zig vem com cabeçalhos libc e conjuntos de ferramentas de compilação cruzada para todos os principais alvos — não é necessário um compilador cruzado separado.

Interoperabilidade C

// Import C header
const c = @cImport({
    @cInclude("stdio.h");
});

// Link C library
pub fn main() void {
    _ = c.printf("hello %d\n", 42);
}

// Direct use of C ABI
extern "c" fn strlen(s: [*:0]u8) usize;

// Zig is a better C:
// - @cImport for headers
// - export fn for C-ABI exports
// - [*:0]T for null-terminated strings
// - @ptrCast for pointer conversion
// - packed struct for ABI-compatible layouts

Diferenças notáveis ​​de C

Compilação

zig build-exe main.zig     # compile executable
zig build-lib lib.zig       # compile library
zig build-obj obj.zig       # compile object
zig run main.zig            # compile + run
zig test file.zig           # compile + run tests
zig fmt file.zig            # format code
zig build                   # build project (build.zig)
zig translate-c foo.h       # translate C header to Zig

Modos de construção

Modo Bandeira Verificações de segurança Otimizações
Depurar (padrão) Completo Nenhum
LiberarSeguro -Doptimize=ReleaseSafe Completo Velocidade
Liberação rápida -Doptimize=ReleaseFast Nenhum Velocidade
Lançamento Pequeno -Doptimize=ReleaseSmall Nenhum Tamanho