Confused with IF syntax

I’m currently learning Zig and I’ve come across a code example that I’m trying to understand. Here’s the code:

fn sayHelloMaybeEdOrError(name: []const u8) void {
    if (dudeIsMaybeEdOrError(name)) |maybe_ed| {
        if (maybe_ed) |ed| {
            std.debug.print("ed? {}\n", .{ed});
            if (ed) {
                std.debug.print("hello {s}\n", .{name});
            } else {
                std.debug.print("hello again {s}\n", .{name});
            }
        } else {
            std.debug.print("goodbye {s}\n", .{name});
        }
    } else |err| {
        std.debug.print("got error: {}!\n", .{err});
        std.debug.print("hello world!\n", .{});
    }
}

From my understanding:

  1. The if statement in Zig doesn’t capture any value when used with a boolean expression.
  2. When used with an optional (?) type, the if statement captures a value only after the if clause.
  3. When used with an error (!) type, the if statement captures a value after both the if and else clauses.

I find this to be a neat syntactic sugar, but it’s a bit confusing to see the if statement being “overloaded” in this way.

1 Like

Could you give the Full code containing all the functions for better understanding, please?

Nice - looks like you’re understanding it so far. I’m going to leave this here because you may find it helpful: Captures and Payloads

In terms of that example, I personally wouldn’t structure it that way (I understand it’s a learning resource and is demonstrating different uses of if).

Looking at the capture page, you’ll see different ways to capture errors. Let’s restructure a few things here:

// handle the error
const maybe_ed = dudeIsMaybeEdOrError(name) catch |err| {
    return std.debug.print("got error: {}!\n", .{err});
};

Then you can inspect your result with an if statement. Just some food for thought, but I think you’re getting the idea so far :slight_smile:

1 Like

Hello @ziggon welcome to ziggit :slight_smile:

Your understanding is correct.

The example is really confusing, but in practice capturing is readable.

1 Like

So, it’s not if specific.
Thank you for the resource!

1 Like