Error: no field named 'cb' in struct 'main.Foo'

Hey all, I’m quite new to zig and was wondering why this code:

const std = @import("std");

pub fn main() !void {
    var doo = Foo{};
    doo.run();
}

const Foo = struct {
    pub fn run(self: *Foo) void {
        run_cb(self.cb);
    } 
    pub fn cb(_: *Foo, val: i32) void {
        std.debug.print("{d}",.{val});
    }
};

fn run_cb(cb: *const fn (v: i32) void) void {
   cb(2);
  }  

Gave this error:

main.zig:11:21: error: no field named 'cb' in struct 'main.Foo'
main.zig:9:13: note: struct declared here (exit status 1)

This is a simplified version of my code but any help or pointers to articles to read on would be super appreciated. BTW just calling the self.cb in the run function works fine it’s only when it’s passed to an external function.
Thanks :slight_smile:

1 Like

TL;DR: structs are not classes, and functions inside structs are not methods but just namespaced functions with a ‘self’ pointer.

You basically need to change run_cb so that it takes a Foo pointer in addition to the function pointer, for instance like this:

3 Likes