Zig Error: unable to resolve comptime value
error: unable to resolve comptime value means Zig needed to know a value while compiling, and you gave it one that’s only known while the program runs. The classic case is an array whose size is a var: var buf: [n]u8. Others are a format string chosen at runtime, or a runtime value passed to a comptime parameter. The note under the error says which rule you hit. For the other errors in this series, see Zig Errors Explained.
The error message
Section titled “The error message”const std = @import("std");
pub fn main() void { var n: usize = 3; n += 1; var buf: [n]u8 = undefined; _ = &buf;}main.zig:6:15: error: unable to resolve comptime value var buf: [n]u8 = undefined; ^main.zig:6:15: note: types must be comptime-knownThe note explains it: [n]u8 is a type (an array of exactly n bytes), and types must be known while compiling. But n is a var that changes at runtime.
What it means
Section titled “What it means”Zig splits values into two kinds:
- Comptime-known: the compiler can work it out while building. Number literals,
constnames set from them, string literals, types. - Runtime-known: only exists when the program runs. Any
var, function parameters (unless markedcomptime), user input, file contents, lengths of things you allocate.
Some places in Zig accept only comptime-known values: array sizes, types, format strings, and parameters marked comptime. That’s how Zig can check format strings and lay out arrays before your program starts. The comptime section of the language reference explains the idea, and our Zig Comptime lesson walks through it.
So the fix depends on the question: can this value be known while compiling?
How to fix it
Section titled “How to fix it”Fix 1: Make it a const (if it’s fixed)
Section titled “Fix 1: Make it a const (if it’s fixed)”If the size never changes, say so. A const set from a literal is comptime-known:
const std = @import("std");
pub fn main() void { const n = 4; var buf: [n]u8 = undefined; @memset(&buf, '*'); std.debug.print("{s}\n", .{&buf});}Output:
****Constants at the top of a file (const max_players = 8;) work the same way and are a good home for sizes like this.
Fix 2: Allocate when the size is only known at runtime
Section titled “Fix 2: Allocate when the size is only known at runtime”If the size really comes from runtime (user input, a file, a calculation on a var), an array can’t hold it. Ask an allocator for a slice of that length instead:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var n: usize = 3; n += 1; const buf = try gpa.alloc(u8, n); defer gpa.free(buf); @memset(buf, '*'); std.debug.print("{s} ({d} bytes)\n", .{ buf, buf.len });}Output:
**** (4 bytes)gpa.alloc(u8, n) returns a []u8 whose length is decided while the program runs. Every allocation needs a matching free, which is what the defer is for. If you know C, this is the difference between char buf[4] and malloc(n); Zig has no variable-length arrays on the stack. See Zig Allocators.
Fix 3: Use a big enough buffer and slice it
Section titled “Fix 3: Use a big enough buffer and slice it”If you know an upper limit, a fixed array plus a slice of the part you use avoids allocating:
const std = @import("std");
pub fn main() void { var n: usize = 3; n += 1; var storage: [64]u8 = undefined; const buf = storage[0..n]; @memset(buf, '*'); std.debug.print("{s} ({d} bytes)\n", .{ buf, buf.len });}Output:
**** (4 bytes)storage[0..n] is a slice, and slices can have a runtime length. If n were ever bigger than 64, the slice would panic in debug builds with an out-of-bounds error, so check the limit first when n comes from outside. See Zig Slices.
Fix 4: Keep format strings and comptime arguments literal
Section titled “Fix 4: Keep format strings and comptime arguments literal”std.debug.print takes its format string as a comptime parameter, so the compiler can check it against the values. A format string picked at runtime gives the same error with a different note:
const std = @import("std");
pub fn main() void { var loud = true; _ = &loud; const fmt = if (loud) "HELLO {s}!\n" else "hello {s}\n"; std.debug.print(fmt, .{"Ada"});}main.zig:7:21: error: unable to resolve comptime value std.debug.print(fmt, .{"Ada"}); ^~~main.zig:7:21: note: argument to comptime parameter must be comptime-known.../lib/std/debug.zig:323:14: note: parameter declared comptime herepub fn print(comptime fmt: []const u8, args: anytype) void { ^~~~~~~~Move the choice outside the call, so each print has a literal format string:
const std = @import("std");
pub fn main() void { var loud = true; _ = &loud; if (loud) { std.debug.print("HELLO {s}!\n", .{"Ada"}); } else { std.debug.print("hello {s}\n", .{"Ada"}); }}Output:
HELLO Ada!The same goes for your own functions with comptime parameters: fn zeros(comptime n: usize) [n]u8 can’t be called with a var. Pass a constant, or change the function to take a runtime n and return a slice instead. If the varying part is just text, keep the format string fixed and pass the text as a value: print("{s}\n", .{message}).
Where you’ll usually see it
Section titled “Where you’ll usually see it”- Arrays sized by a
var, a parameter or input:[n]u8. Use an allocator or a fixed buffer. - Format strings built or chosen at runtime.
- Generic functions (
comptime T: type,comptime n: usize) called with runtime values. - Inside the standard library: sometimes the error points into
lib/std/with a note leading back to your call. Follow the notes to your line; it’s usually the same mistake. See Zig Comptime.
Related errors
Section titled “Related errors”- variable of type ‘comptime_int’ must be const or comptime: the reverse, a compile-time-only value stored in a runtime
var. - index out of bounds: what Fix 3 can turn into at runtime if
nis too big. - expected type ‘X’, found ‘Y’: passing a slice where a fixed-size array type is needed.
- All Zig error pages: the full list.
Practice
Section titled “Practice”1. A line of dashes
Section titled “1. A line of dashes”width comes from a calculation at runtime. Make the program print ---------- (10 dashes) using an allocator.
const std = @import("std");
pub fn main(init: std.process.Init) !void { var width: usize = 5; width *= 2; var line: [width]u8 = undefined; @memset(&line, '-'); std.debug.print("{s}\n", .{&line});}Hint: init.gpa.alloc(u8, width) gives you a slice. Don’t forget to free it.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var width: usize = 5; width *= 2; const line = try gpa.alloc(u8, width); defer gpa.free(line); @memset(line, '-'); std.debug.print("{s}\n", .{line});}Output:
----------The slice’s length is set at runtime, which an array type can’t do. line is already a slice, so @memset and print take it directly, without &.
- Some places need comptime-known values: array sizes, types, format strings,
comptimeparameters. - A
var, a parameter or anything from input is runtime-known. - Size fixed? Use a
const. Size from runtime? Allocate a slice, or slice a big enough buffer. - Keep format strings literal: branch around the
printinstead of choosing the string. - The note tells you which rule you hit:
types must be comptime-knownorargument to comptime parameter must be comptime-known.
Next up: integer overflow, the panic you get when a number doesn’t fit its type.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- comptime in the Zig language reference: compile-time values and parameters.
- Compile-time parameters in the Zig language reference: what
comptimeon a parameter means. - Arrays in the Zig language reference: array sizes are part of the type.
- Zig Comptime: our lesson on compile-time code.