#Get reference to function from a member function

1 messages · Page 1 of 1 (latest)

muted mantle
#

Hi, I have a struct and inside one function1 that does nothing, one that tries to return reference to a self.function1 and the last one wants to call the function1() when function2 returns it. However in the second function that tries to return self.function1 it throws compile error saying there is no member field function1.

Any ideas?

somber thistle
#

show the code, its very hard to understand this without the context

west brook
#

I'm assuming from the text you have something like

const T = struct {
    fn function1(_: T) void {}
    fn function2(t: T) *const fn (T) void {
        return t.function1;
    }
    fn function3(t: T) void {
        return t.function2()();
    }
};
#

The reason this doesn't work is because t.foo is only valid syntax for actual fields

#

"methods" are not an actual concept in zig

#

t.func(...) is simply syntax sugar for @TypeOf(t).func(t, ...)

#

And it is specifically that

#

It can't be (t.func)(...) or any other deconstruction

#

So the solution would be to change function2 to simply return T.function1

muted mantle
west brook
#

I don't understand the question

#

What are you trying to do

fallen python
#

There's no problem with function2 branching if that's what you're asking. The new code would look something like this:

fn function1(_: T) void {}
fn function2() *const fn (t: T) void {
    return T.function1;
}
fn function3(t: T) void {
    return T.function2()(t);
}
#

Of course function2 can still itself be a method if its behaviour depends on t

fallen python
#

The key thing to understand here is that "methods" aren't anything special in Zig - they're literally just functions whose first parameter happens to line up with the container type they're in. So t.function1 as a standalone expression is entirely meaningless - it only makes sense in the context of the sugar for a call

muted mantle
#
const ParseFn = *const fn (self: *Parser) void;

pub const Parser = struct {
            fn group(self: *Parser) void {
        _ = self;
    }

        fn getRule(self: *Self, t_type: Token.Type) ParseRule {
        return switch (t_type) {
            .left_paren => .{ .prefix = self.group },

            else => unreachable,
        };
    }
};

#

I got the code like this, but it doesnt work and I dont see how I should implement your solution

west brook
#

.{ .prefix = self.group } -> .{ .prefix = Parser.group }

#

as stated before, value.method() is purely syntactic sugar over @TypeOf(value).method(value)

#

any deconstruction of that syntax is not

#

self.group isn't valid, because there is no group field

muted mantle
#

Ahaa, got it

#

Its working now