Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There's nothing special about the 'Self' (it's just a type).

In general, consts in Zig are purely compile time things and don't take up memory.

And putting a function inside a struct which takes a pointer to its struct type as first argument just allows method-call-syntax-sugar, but you can also write it as regular function (which must then be namespaced with the struct type though):

    const Bla = struct {
        const Self = @This();
        val: i32 = 0,
        fn add(self: *Self, val: i32) void {
            self.val += val;
        }
    };

    pub fn main() void {
        var bla = Bla{};
        // with method-call syntax sugar
        bla.add(2);
        // without method-call syntax sugar
        Bla.add(&bla, 3);
    }
...but in this case it's probably better to not use Self and @This() (it mostly makes sense with generics).

    const Bla = struct {
        val: i32 = 0,
        fn add(self: *Bla, val: i32) void {
            self.val += val;
        }
    };


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: