How to put a function pointer into a struct

Hi,

I’m new to Zig, and I think I need some hints into the right direction. So…

I have a struct

const WriteJob = struct {
    priority: i64,
    task: *WriteTask,
};

and WriteTask is declared as

const WriteTask = fn (params: []const u8) void;

and I have defined 2 functions:

fn writeCustomer(params: []const u8) void {
    std.debug.print("Customer {s}", .{params});
}

fn writeInvoce(params: []const u8) void {
    std.debug.print("Invoice No. {s} ", .{params});
}

In the main function I want to create an Arraylist with 1 or more entries of that struct WriteJob.

pub fn main() !void {
    var queue = std.ArrayList(WriteJob).init(allocator);

    queue.append(.{ .priority = 100, .task = writeCustomer("Norbert Nudel") });
}

When I compile that, I got the following error:

src/main.zig:30:44: error: expected type '*fn ([]const u8) void', found 'void'
    queue.append(.{ .priority = 100, .task = writeCustomer("Norbert Nudel") });

Maybe someone can show me a solution to put that function into a struct.

BR smf

Firstly, function pointers should be const: *const WriteTask.

If you want to store a function pointer, you would do .task = &writeCustomer. What you’re doing is actually calling the function, and then trying to assign the return value of the function (void) to the field.

If you want to be able to store all the information needed for a later call to that function, you could store the parameters in WriteJob like so:

const WriteJob = struct {
    priority: i64,
    task: *const WriteTask,
    params: []const u8,
}

Then, when you want to actually run the job, you can call the function pointer with the parameters you stored earlier. You just make sure that the memory params points to lives until the job is run.

7 Likes

Hi n0s4

Thank you very much :+1:

Your help is really appriciated!

BR smf