Compilation error printing single command line argument

Hi Folks,

I have just starting playing around with Zig and found the following code which works for printing a program’s command line arguments:

const std = @import("std");

pub fn main(init: std.process.Init) void {
    
    var args_iter = try init.minimal.args.iterateAllocator(init.gpa);
    defer args_iter.deinit();

    var i: usize = 1;
    _ = args_iter.skip();
    while (args_iter.next()) |arg| {
        std.debug.print("arg {d}: \"{s}\"\n", .{i, arg });
        i += 1;
    }
}

I tried the following modification to print just the first command line argument without looping:

const std = @import("std");

pub fn main(init: std.process.Init) void {
    
    var args_iter = try init.minimal.args.iterateAllocator(init.gpa);
    defer args_iter.deinit();

    _ = args_iter.skip();
    const arg = args_iter.next();
    std.debug.print("arg = {s}\n", .{arg}); 
}

However, this gives me a compilation error:

zig-x86_64-linux-0.17.0/lib/std/Io/Writer.zig:1935:5: error: 
invalid format string 's' for type '?[:0]const u8'

I would appreciate any help understanding why the error only occurs on the second program. Thanks!

args_iter.next() returns an optional (note the ? in the type name the error gives you). You’re required to unwrap optionals before working with them, which is what you’re doing with the while loop in the first example. You can replace while with if in there, which will get you the desired result (and then you can add an else to it to do something when the argument is not present)

Thanks for the help! This works:

if(arg) | value | {
        std.debug.print("arg = {s}\n", .{value});
}

Formatting supports optionals with {?}, and you can add another for the non-null value {?s}

I see that this will print either a string or ‘null’:

std.debug.print("arg = {?s}\n", .{arg});

Where would you use {?} by itself?

When you want to use the default formatting for the non-null type.