🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Comptime Strings

A comptime string is a string whose value is fully known during compilation. It can be built from pieces before the program runs, so the program prints text that was already assembled.

Combining pieces

Two comptime strings combine into one longer comptime string, and its length is known at once.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const greeting = "Hello, " ++ "world!";
    try out.print("{s}\n", .{greeting});
    try out.print("len={d}\n", .{greeting.len});
}

A slice at compile time

Slicing a comptime string keeps only the chosen characters, and the result is still known during compilation.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const text = "hello world";
    const word = text[0..5];
    try out.print("{s}\n", .{word});
    try out.print("len={d}\n", .{word.len});
}

Formatted at compile time

A comptime formatting call inserts a number into text during compilation.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const label = comptime std.fmt.comptimePrint("lesson-{d}", .{5});
    const count = comptime std.fmt.comptimePrint("count={d}", .{3});
    try out.print("{s}\n", .{label});
    try out.print("{s}\n", .{count});
}

Example

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const base = "zig-";
    const ver = comptime std.fmt.comptimePrint("{d}", .{14});
    const full = base ++ ver;
    const mark = "ab" ** 3;
    try out.print("{s}\n", .{full});
    try out.print("{s}\n", .{mark});
    try out.print("full-len={d}\n", .{full.len});
}

Key points

  • Comptime string: a comptime string is a string whose value is fully known during compilation.
  • Concatenation: concatenation is combining two strings into one longer string.
  • Slice: a slice is a view of part of a string, such as its first five characters.
  • Length: length is the number of characters in a string.
  • Formatted text: formatted text is text built by inserting a value into a fixed template.
  • Repetition: repetition is repeating a short string a fixed number of times to make a longer string.

The example builds a version label from a prefix and a formatted number. It also repeats a short string three times. Both results were fixed during compilation, so the program only prints them.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which value is a comptime string?