#Recommendations on how to make this code less awful.

1 messages · Page 1 of 1 (latest)

quaint sage
#
// Same as std.ArrayList.popOrNull except error.ArrayListUnderflow is returned instead of null
fn popOrError(array_list: anytype) !@TypeOf(array_list.items[0]) {
    if (@TypeOf(array_list.*) != std.ArrayList(@TypeOf(stack.items[0]))) {
        @compileError("array_list must be a std.ArrayList");
    }
    return if (array_list.popOrNull()) |res| res else error.ArrayListUnderflow;
}
#

I'm thinking something like fn popOrError(comptime T: type, array_list: *std.ArrayList(T)) T { ... } would be much cleaner but it'd be nice if I didn't have to pass the type in.

ancient wasp
#

agreed

#

also, the return can be array_list.popOrNull() orelse error.ArrayListUnderflow

covert olive
#

why not just do array_list.popOrNull() orelse error.ArrayListUnderflow instead of this function?

ancient wasp
#

maybe they want to try in a lot of places

covert olive
#

you can do try list.popOrNull() orelse error.ArrayListUnderflow; I think

quaint sage
#

Yep. I was doing something similar to list.popOrNull() orelse error.ArrayListUnderflow (except I forgot orelse existed) a lot so I tried extracting it into a function, and this was a result.