#Anonymous function?

1 messages · Page 1 of 1 (latest)

upbeat ruin
#

How do folks write anonymous functions in Zig?

I wrote the following this zls seemed to not display any errors.

    root.visitDirs(fn (n: *Node) void {
        if (n.typ == .dir) {
            print("{s}: {d}", .{ n.name, n.totalSize() });
        }
    });

But when I run it, I see this:

main.zig:56:13: error: use of undeclared identifier 'n'
        if (n.typ == .dir) {

n is clearly defined in the parameter list of the function, so I'm guessing I'm writing anonymous functions incorrectly.

urban falcon
#

simple answer: you can't

#

also, zls is not a litmus test for code validity, fair warning :)

#

slightly more complex answer: use a struct hack!

#
const myFn = struct {
  pub fn myFn(abc: Def) Ghi { ... }
}.myFn;
#

not sure if this still works with all the stage2 going on atm but it's how it's always worked :)

upbeat ruin
#

Oh my, I've used that hack once facepalm I forgot about it. Ugh.

upbeat ruin
urban falcon
#

kinda

#

the anonymity isn't really the blocker

#

moreso scope issues

#

and access to locals

#

it's weird

upbeat ruin
#

Got it.

#

So a learning from this is that instead of writing closures that capture state, I need to pass a "context" of sorts down to functions I'm calling, and I can make that context anytype.