-1

I want to modify or compute a value before assigning it to a const. Is there a way to do this in a single line expression?

I can use labeled block syntax, but I’m wondering if there’s another syntax that would be easier to read.

const std = @import("std");

const print = std.debug.print;

fn f(x: i32) i32 {
    return x + 1;
}

pub fn main() void {
    {
        const x, const y = blk: {
            const a = f(2);

            break :blk .{ a * a, a + a };
        };
        print("{d}, {d}\n", .{ x, y });
    }

    {
        // Is there a way to do something like this
        // const x, const y = f(2) |a| .{ a * a, a + a };
        // print("{d}, {d}\n", .{ x, y });

        // Not like this
        const x, const y = if (@as(?i32, f(2))) |a| .{ a * a, a + a } else unreachable;
        print("{d}, {d}\n", .{ x, y });
    }

    {
        // Is there a way to do something like this
        // f(2) |a| .{ a * a, a + a } |x,y| print("{d}, {d}\n", .{ x, y });

        // Not like this
        if (@as(?struct { i32, i32 }, if (@as(?i32, f(2))) |a| .{ a * a, a + a } else unreachable)) |a| print("{d}, {d}", .{ a.@"0", a.@"1" }) else unreachable;
    }
}
New contributor
Phuwadon Verasertniyom is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

0

No, there is not. Zig is not a functional programming language.

Do this instead:

const a = f(2);
const x = a * a;
const y = a + a;
print("{d}, {d}\n", .{ x, y });

Or this:

const a = f(2);
print("{d}, {d}\n", .{ a * a, a + a });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.