1. 41
  1.  

  2. 26

    I looked at the source and thought I’d share some neat things that you can do.

    Instead of

    var bin_name = args.nextPosix();
    

    you can do

    _ = args.nextPosix();
    

    to ignore the value, and get rid of the unused variable.

    Instead of

    var fname = args.nextPosix();
    if (fname == null) {
        std.debug.warn("expected at least one file name as an argument\n", .{});
        std.os.exit(1);
    }
    
    if (readFile(fname.?))
    

    you can do

    var fname = args.nextPosix() orelse {
        std.debug.warn("expected at least one file name as an argument\n", .{});
        std.os.exit(1);
    }
    // `orelse` has already "unwrapped" the optional, so no need for `.?`
    if (readFile(fname))
    

    Instead of

    if (readFile(name)) |_| {} else |err| {
        std.debug.warn("error reading file: {}\n", .{err});
    }
    

    you can do

    readFile(name) catch |err| {
        std.debug.warn("error reading file: {}\n", .{err});
    }
    

    which is a bit nicer, IMO.

    And of course, if you want, you can make main return !void, and use try directly in it.

    1. 3

      This is really helpful! I appreciate the feedback. I will need to read more about the orelse keyword.

      1. 3

        I’m not that familiar with Zig yet, but I prefer your adjustments here. Thanks and thanks to gsquire for putting it together.

      2. 6

        Thanks for putting this together. As someone who is unfamiliar with Zig, your choice of implementing a known utility rather than something less familiar allowed me to focus on what I don’t know about Zig, rather than the use case. Cheers.

        1. 1

          I’m glad you enjoyed it and thanks for reading!

        2. 3

          Something I noticed with the warn function is that it requires a second argument regardless if you use a format specifier or not. Perhaps that is a design decision or maybe a limitation of the current implementation.

          If I recall correctly, Zig has purposely no function overloading, therefore to use the function std.debug.warn you must provide its second argument which is an anonymous struct used for the string interpolation.*

          std.debug.warn("two three", .{});
          
          1. 1

            IIRC, there used to be varargs, and you could call it with one argument, but it was removed to simplify the language. It’s good that varargs are gone, IMO, even if it’s sometimes annoying to add .{}. I should add a shortbut for it.