#Trying to work with anytype

1 messages · Page 1 of 1 (latest)

bronze monolith
#

I have the following snippet:

...
    pub fn advance(self: *Parser, performer: anytype, byte: u8) void {
        self.advance_state(byte);

        switch (self.action) {
            .DISPATCH_PRINTABLE => {
                performer.dispatch_printable(byte);
            },
            else => {
                unreachable;
            },
        }
    }
...
};

test "Parse a " {
    var test_parser = Parser{};
    const test_input = "Lorem ipsum odor amet, consectetuer adipiscing elit.";

    const ImplPerformer = struct {
        const Self = @This();

        buffer: [64]u8 = undefined,
        idx: usize = 0,

        pub fn dispatch_printable(self: *Self, byte: u8) void {
            self.buffer[self.idx] = byte;
            self.idx += 1;
        }
    };

    var performer = ImplPerformer{};

    for (test_input) |c| {
        test_parser.advance(performer, c);
    }
    try testing.expectEqualSlices(u8, test_input[0..52], performer.buffer[0..52]);
}

I have 2 questions: First I get the following error which tells me I don't really understand anytype:

src/parser.zig:106:26: error: expected type '*parser.test.Parse a .ImplPerformer', found '*const parser.test.Parse a .ImplPerformer'
                performer.dispatch_printable(byte);
                ~~~~~~~~~^~~~~~~~~~~~~~~~~~~
src/parser.zig:106:26: note: cast discards const qualifier
src/parser.zig:131:41: note: parameter type declared here
        pub fn dispatch_printable(self: *Self, byte: u8) void {

Second, i would like to all the dispatch_*** function in a struct inside ImplPerformer and have those function modify the parent struct. Do you think it is possible?

olive hill
#

the issue with the const / non-const pointer here is that performer, in function advance, is an argument, those are marked const, so getting a reference to it results in a *const …

in the test, you can pass in &performer instead of performer - that is, a reference to the performer defined in the test block.
the current behaviour copies performer instead of getting a reference to the value.

bronze monolith
#

Oh, thanks. Usually I do the opposite and make the argument of the function a pointer