Skip to content

Calling try with a non-error-union argument, could suggest dropping the try call #21845

@mark-rushakoff

Description

@mark-rushakoff

Zig Version

0.14.0-dev.2050+4adf63aef

Steps to Reproduce and Observed Output

I mistakenly thought that ArrayList.init could fail to allocate, so I prefixed it with try:

// a.zig

const std = @import("std");

pub fn main() void {
    const list = try std.ArrayList(u8).init(std.heap.page_allocator);
    std.debug.print(list.capacity);
}

This resulted in this error:

/tmp/a.zig:6:44: error: expected error union type, found 'array_list.ArrayListAligned(u8,null)'
    const list = try std.ArrayList(u8).init(std.heap.page_allocator);
                     ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~

I am still learning Zig, so it took me a minute to interpret the error message and understand that try was what was wrong/unnecessary on that source line.

Expected Output

The inverse of this mistake -- a call that returns an error union which is unhandled -- offers a note suggesting how to address the compile error:

/tmp/b.zig:7:16: error: error union is ignored
    list.insert(0, 0);
    ~~~~~~~~~~~^~~~~~
/tmp/b.zig:7:16: note: consider using 'try', 'catch', or 'if'

The original mistake I made of using try when it is unnecessary, could output a suggestion to drop the try:

/tmp/a.zig:6:44: error: expected error union type, found 'array_list.ArrayListAligned(u8,null)'
    const list = try std.ArrayList(u8).init(std.heap.page_allocator);
                     ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
/tmp/a.zig:6:44: note: consider omitting 'try'

The note is obviously much easier for a human to parse, and it would be particularly helpful to new Zig users.

I looked through Sema.zig but did not see any existing calls to sema.errNote that suggest removing a call, so I am not sure if there is precedence on exact phrasing for this case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    error messageThis issue points out an error message that is unhelpful and should be improved.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions