Zig Error: expected type 'X', found 'Y'
error: expected type 'X', found 'Y' means a value of type Y ended up somewhere that needs type X, and Zig won’t convert it for you. It’s the most common Zig error after the unused-name family, because Zig converts almost nothing on its own: no hidden casts from i64 to i32, no turning an optional into a plain value, no ignoring an error. The good news is that a handful of type pairs cover most cases, and the notes under the error usually tell you the fix. For the other errors in this series, see Zig Errors Explained.
The error message
Section titled “The error message”const std = @import("std");
fn shout(text: []u8) void { std.debug.print("{s}!\n", .{text});}
pub fn main() void { shout("hello");}main.zig:8:11: error: expected type '[]u8', found '*const [5:0]u8' shout("hello"); ^~~~~~~main.zig:8:11: note: cast discards const qualifiermain.zig:3:16: note: parameter type declared herefn shout(text: []u8) void { ^~~~Read it in three parts:
expected type '[]u8'is what the spot needs. It comes from your code: a type after a colon, a function parameter, or a return type. The last note shows exactly where it was declared.found '*const [5:0]u8'is the type of the value you gave.*const [5:0]u8is how Zig spells a string literal: a read-only pointer to 5 bytes with a0at the end.- The notes explain why the conversion isn’t allowed. Here: it would drop
const, which would letshoutchange read-only memory.
What it means
Section titled “What it means”Zig checks the type of every value against the type of the place it goes. Some conversions are safe and happen by themselves: a u8 fits in a u32, an array turns into a slice, a u32 becomes a ?u32. Anything that could lose information, hide an error or skip a null check has to be written out. The type coercion section of the language reference lists the automatic ones.
So the question for every fix is: which side is wrong? Sometimes the declared type X should change; sometimes the value needs handling first. Here are the pairs you’ll meet most.
| found / expected | What happened | Usual fix |
|---|---|---|
*const [N:0]u8 / []u8 |
String literal where a changeable slice is needed | Use []const u8 |
error{...}!T / T |
A call that can fail, used as a plain value | try |
?T / T |
An optional, used as a plain value | orelse, if, .? |
i64 / i32 |
A bigger integer into a smaller one | Bigger type, or @intCast |
usize / f64 |
An integer where a float is needed | @floatFromInt |
u8 / []const u8 |
A number where text is needed | Format it with {d} |
How to fix it
Section titled “How to fix it”Fix 1: Use []const u8 for strings you only read
Section titled “Fix 1: Use []const u8 for strings you only read”If a function only reads a string, its parameter should be []const u8. That’s the normal string type in Zig:
const std = @import("std");
fn shout(text: []const u8) void { std.debug.print("{s}!\n", .{text});}
pub fn main() void { shout("hello");}Output:
hello![]u8 means “I will change these bytes”. Ask for that only when the function really edits the text, and then pass a copy you own, not a literal. Zig Strings explains the string types.
Fix 2: Add try for a call that can fail
Section titled “Fix 2: Add try for a call that can fail”const std = @import("std");
pub fn main() void { const n: u32 = std.fmt.parseInt(u32, "42", 10); std.debug.print("{d}\n", .{n});}main.zig:4:36: error: expected type 'u32', found 'error{InvalidCharacter,Overflow}!u32' const n: u32 = std.fmt.parseInt(u32, "42", 10); ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~main.zig:4:36: note: cannot convert error union to payload typemain.zig:4:36: note: consider using 'try', 'catch', or 'if'The ! in the found type means “an error or a u32”. This is an error union, and Zig makes you deal with the error part. try passes the error up to the caller, so main has to be able to return one: its return type becomes !void.
const std = @import("std");
pub fn main() !void { const n: u32 = try std.fmt.parseInt(u32, "42", 10); std.debug.print("{d}\n", .{n});}Output:
42catch lets you use a fallback instead: parseInt(...) catch 0. See Zig Try and Catch.
Fix 3: Unwrap an optional
Section titled “Fix 3: Unwrap an optional”const std = @import("std");
fn findAge(name: []const u8) ?u32 { if (std.mem.eql(u8, name, "Ada")) return 36; return null;}
pub fn main() void { const age: u32 = findAge("Ada"); std.debug.print("{d}\n", .{age});}main.zig:9:29: error: expected type 'u32', found '?u32' const age: u32 = findAge("Ada"); ~~~~~~~^~~~~~~main.zig:9:29: note: cannot convert optional to payload typemain.zig:9:29: note: consider using '.?', 'orelse', or 'if'The ? means the value might be null. Decide what happens then. orelse gives a default:
const std = @import("std");
fn findAge(name: []const u8) ?u32 { if (std.mem.eql(u8, name, "Ada")) return 36; return null;}
pub fn main() void { const age: u32 = findAge("Ada") orelse 0; const other: u32 = findAge("Bob") orelse 0; std.debug.print("{d} {d}\n", .{ age, other });}Output:
36 0if (findAge("Bob")) |a| { ... } else { ... } runs different code for each case. .? says “I’m sure it isn’t null” and crashes if you’re wrong: see attempt to use null value. Zig Optionals has all three.
Fix 4: Integers of different sizes
Section titled “Fix 4: Integers of different sizes”const std = @import("std");
fn half(n: i64) i32 { return @divTrunc(n, 2);}
pub fn main() void { std.debug.print("{d}\n", .{half(10)});}main.zig:4:12: error: expected type 'i32', found 'i64' return @divTrunc(n, 2); ^~~~~~~~~~~~~~~main.zig:4:12: note: signed 32-bit int cannot represent all possible signed 64-bit valuesmain.zig:3:17: note: function return type declared herefn half(n: i64) i32 { ^~~The note says it: an i64 can hold numbers an i32 can’t. The cleanest fix is often to use the same type on both sides (here, return i64). If you know the value fits, say so with @intCast, which takes its target type from where the result goes:
const std = @import("std");
fn half(n: i64) i32 { return @intCast(@divTrunc(n, 2));}
pub fn main() void { std.debug.print("{d}\n", .{half(10)});}Output:
5If the value doesn’t fit, @intCast panics in debug builds. When it might not fit, use std.math.cast(i32, x), which returns null instead. Zig Type Casting covers every cast.
Fix 5: Integers into floats
Section titled “Fix 5: Integers into floats”const std = @import("std");
pub fn main() void { const scores = [_]u32{ 7, 9, 8 }; var total: u32 = 0; for (scores) |s| total += s; const avg: f64 = total / scores.len; std.debug.print("{d}\n", .{avg});}main.zig:7:28: error: expected type 'f64', found 'usize' const avg: f64 = total / scores.len; ~~~~~~^~~~~~~~~~~~total / scores.len is integer division, and its result is a usize. Turn each side into a float first, then divide:
const std = @import("std");
pub fn main() void { const scores = [_]u32{ 7, 9, 8 }; var total: u32 = 0; for (scores) |s| total += s; const avg: f64 = @as(f64, @floatFromInt(total)) / @as(f64, @floatFromInt(scores.len)); std.debug.print("{d}\n", .{avg});}Output:
8Converting after the division would be a quiet bug: 7 / 2 as integers is 3, and turning 3 into a float gives 3.0, not 3.5.
Fix 6: Numbers aren’t text
Section titled “Fix 6: Numbers aren’t text”const label: []const u8 = age; with age: u8 gives expected type '[]const u8', found 'u8'. A number isn’t a string in Zig, not even a one-byte one. To show it, print it with {d}. To build a string from it, format into a buffer:
const std = @import("std");
pub fn main() !void { const age: u8 = 30; var buf: [16]u8 = undefined; const label = try std.mem.print(&buf, "{d} years", .{age}); std.debug.print("{s}\n", .{label});}Output:
30 yearsstd.mem.print fails with an error if the buffer is too small, hence the try. Zig Format Strings lists the placeholders.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- String parameters declared as
[]u8instead of[]const u8. - Calling a function that returns
!Tor?Tand storing the result asT. - Mixing integer types:
usizefrom.lenwithu32ori32counters. - Averages and percentages, where integers meet floats.
- Code written for an older Zig, where a standard library function’s types have changed since.
Related errors
Section titled “Related errors”- expected error union type, found ‘X’: the opposite of Fix 2,
tryon something that can’t fail. - error union of type ‘X’ is ignored: calling a function that can fail without using its result.
- variable of type ‘comptime_int’ must be const or comptime: a
varthat needs a type. - All Zig error pages: the full list.
Practice
Section titled “Practice”1. Percent done
Section titled “1. Percent done”This program should print 75%. Fix the type error without changing the type of done or total.
const std = @import("std");
pub fn main() void { const done: usize = 3; const total: usize = 4; const percent: f64 = done * 100 / total; std.debug.print("{d}%\n", .{percent});}Hint: convert done and total to f64 before you do the maths.
Show solution
const std = @import("std");
pub fn main() void { const done: usize = 3; const total: usize = 4; const d: f64 = @floatFromInt(done); const t: f64 = @floatFromInt(total); const percent: f64 = d * 100 / t; std.debug.print("{d}%\n", .{percent});}Output:
75%@floatFromInt takes its target type from the result location, here the f64 after each name. Once both are floats, the division keeps the decimals too.
- Expected is what the spot needs (from your types). Found is what you gave.
- Zig converts only when nothing can be lost. Everything else you write out.
[]u8vs a literal: use[]const u8.!TvsT:try.?TvsT:orelseorif.- Integer sizes: use the same type, or
@intCastwhen it surely fits. Int to float:@floatFromInt. - Read the notes: they usually name the fix.
Next up: error union of type ‘X’ is ignored, the error for a call whose error you didn’t handle.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Type coercion in the Zig language reference: which conversions happen by themselves.
- Explicit casts in the Zig language reference:
@intCast,@floatFromIntand the rest. - Error union type in the Zig language reference: what
!Tmeans. - Zig Type Casting: our lesson on converting between types.