ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.88k stars 2.55k forks source link

Improve messages when implicit casts from array to slice fails due to const mismatch #21967

Open DonIsaac opened 1 day ago

DonIsaac commented 1 day ago

Zig Version

0.13.0

Steps to Reproduce and Observed Output

Minimal reproduction:

const std = @import("std");

fn needsSliceGood(nums: []const u32) void {
    std.debug.print("{any}\n", .{nums});
}
fn needsSliceBad(nums: []u32) void {
    std.debug.print("{any}\n", .{nums});
}

pub fn main() !void {
    const arr = [_]u32{ 1, 2, 3 };
    needsSliceGood(&arr);
    needsSliceBad(&arr); // conversion fails because arr ptr is *const
}

Produces this error message:

src/main.zig:13:19: error: expected type '[]u32', found '*const [3]u32'
    needsSliceBad(&arr);
                  ^~~~
src/main.zig:13:19: note: cast discards const qualifier
src/main.zig:6:24: note: parameter type declared here
fn needsSliceBad(nums: []u32) void {

Expected Output

This message does not inform the programmer about the true nature of the problem: That arr is a const pointer and cannot be converted into a non-const slice.

A possible message could be:

Cannot cast const array of <type> to a non-const slice. Consider making the array mutable or changing <target-var-name> to `[]const <type>`

Where target-var-name is the LHS of an assignment or a function parameter name.

rohlem commented 1 day ago

Note that note: cast discards const qualifier is supposed to already hint at exactly this.