Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DonIsaac opened this issue Nov 11, 2024 · 1 comment
Labels
error message This issue points out an error message that is unhelpful and should be improved.

Comments

@DonIsaac
Copy link

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.

@DonIsaac DonIsaac added the error message This issue points out an error message that is unhelpful and should be improved. label Nov 11, 2024
@rohlem
Copy link
Contributor

rohlem commented Nov 11, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
error message This issue points out an error message that is unhelpful and should be improved.
Projects
None yet
Development

No branches or pull requests

2 participants