Z017: Try in return
Detects return try expr. Assign the tried result to a local before returning it so removing try cannot break an error-union payload coercion.
Examples
Bad
// expect: Z017
fn loadValue() !u32 {
return 1;
}
fn readValue() !u32 {
return try loadValue();
}Good
fn loadValue() !u32 {
return 1;
}
fn readValue() !u32 {
const value = try loadValue();
return value;
}
The try is still needed for non-return statements:
fn process() !void {
const data = try getData(); // try needed here
return transform(data); // no try needed in return
}
The try can be needed when the function return type performs an additional payload coercion, such as returning Thing as ?Thing in an !?Thing function. Hoist it to a local so the coercion is preserved without placing try in the return expression:
const Thing = struct {};
fn allocThing() !Thing {
return .{};
}
fn maybeThing() !?Thing {
const thing = try allocThing();
return thing;
}
Rationale
In Zig, return expr already propagates errors when the function returns a matching error union. However, try is required when the expression's payload must be coerced before returning, such as !Thing to !?Thing or !u32 to !u64. Z017 cannot prove that every expression has a matching payload type, so its diagnostic recommends the semantics-preserving local binding instead of suggesting that try be removed.