Skip to content

Anonymous (unlabeled) block expressions when there is no ambiguity #5382

Closed
@gpanders

Description

@gpanders

Consider the following snippet:

const dir = blk: {                                                                                    
    if (std.os.getenv("FOO_DIR")) |dir| {                                                          
        break :blk try std.mem.dupe(allocator, u8, dir);                                              
    } else if (std.os.getenv("XDG_DATA_HOME")) |xdg_data_home| {                                      
        break :blk try std.fs.path.join(allocator, &[_][]const u8{ xdg_data_home, "foo" });           
    } else if (std.os.getenv("HOME")) |home| {                                                        
        break :blk try std.fs.path.join(allocator, &[_][]const u8{ home, ".local", "share", "foo" }); 
    } else {                                                                                          
        return error.NoFooDirFound;                              
    }                                                                                                 
};                                                                                                    
defer allocator.free(dir);         

In this case, there is no ambiguity in the meaning of break within the block, since there is no parent loop. The repeated blk: and :blk labels add code noise; would it be possible to allow for anonymous/unlabeled blocks when there is no ambiguity? Example:

var y = someFunction();
const x = {
    if (y >= 0) {
        break y * y;
    else {
        break 0;
    }
};

(I realize there are better ways to do the above, it's merely a contrived example).

In cases where there is ambiguity (e.g. in a while or for loop), the labels would still need to be explicitly defined.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions