#Need help understanding pointer args

1 messages · Page 1 of 1 (latest)

spare cipher
#

I'm currently learning Zig and I'm a little thrown off by its pointer handling and resulting compile errors.
As I've worked with C, albeit a long time ago, pointers are not a new concept, but I'm wondering what the best practices are for the following:

e.g. I have a method on a struct like this:

    pub fn parse(self: *Parser) !*Node {}

which I invoke via:

        var parser = Parser.init(...);

        const ast = parser.parse();

however when I change var parser to const parser I get:

src/parser.zig:109:27: error: expected type '*parser.Parser', found '*const parser.Parser'
        const ast = parser.parse();
                    ~~~~~~^~~~~~
src/parser.zig:109:27: note: cast discards const qualifier
src/parser.zig:52:24: note: parameter type declared here
    pub fn parse(self: *Parser) !*Node {

But when I change the method to const pointer:

    pub fn parse(self: *const Parser) !*Node {}

I can now use both var parser = Parser.init(...); or const parser = Parser.init(...);

What's the best practice to use in this case for the method signature?
I guess *const since you don't want to change where self points to, which *Parser would theoretically allow?
Are there situations where I would prefer self: *Parser?

boreal agate
#

Presumably the parser has state. So you should use var parser = ... and *Parser args when modifying state.
That's the short answer, I'm sure Vei is cooking up the long one...