Is there a specific reason that we don't have nested functions

What is the reason that functions can’t have inner functions inside them. Is this simply a design choice? Is it just not within the Zig philosophy? or Is this something that would be done in future?

pub fn addTwo(a: i32) i32 {
    fn addOne (a: i32) i32 {
        return a + 1,
    };

    return addOne(a) + 1;
}

The above is a trivial example but is this ever going to be a thing?

You can accomplish the same thing by creating a struct type inside the function:

pub fn addTwo(a: i32) i32 {
    const Fns = struct {
        fn addOne (b: i32) i32 {
            return b + 1;
        }
    };

    return Fns.addOne(a) + 1;
}

Some of the reasoning behind keeping function declaration syntax distinct from other types is explained in this Git issue comment.

8 Likes

link does not work.

1 Like

My GitHub link? It’s the correct comment permalink and it seems to work in every browser that I’ve tried.

4 Likes

The link works for me.

2 Likes

Are you sure it didn’t work?
Could it be that it worked and you just didn’t like the answer?
:grin:

1 Like

Just commenting to reply in defense of @slonik-az that the link actually is broken (on mobile Safari, anyway). But this appears to be a GitHub or Safari issue, maybe due to there being hundreds of collapsed comments in that issue which messes up the page loading when the link is to a later comment, but that’s just a guess.

Anyway, using a local struct for the function is the correct answer to the original question IMO.

3 Likes

The link does not work on my ipad using Safari browser. moreover it traps the browser so that “go back” button does not work. could be a safari things but annoying like hell.

@obijohn welcome to the forum and thanks for the detailed error report. this is exactly the error i am seeing on my ipad.