#vtable syntax confuses me

1 messages · Page 1 of 1 (latest)

crimson plinth
#
pub fn allocator(self: *Self) Allocator {
    return .{
        .ptr = self,
        .vtable = &.{
            .alloc = alloc,
            .resize = resize,
            .free = free,
        },
    };
}

this excerpt is from std.heap.GeneralPurposeAllocator. in particular, I am confused by the vtable initialization. My newbie eyes are inclined to read this as creating a new allocator vtable on the stack, and taking the address of that, and returning it to the caller. But this obviously works, and so I'd like some help correcti8ng my reading of this.

#

is it just that the vtable is interned because everything is a comptime value?

cerulean spear
#

Yes, it's all comptime so you can return a pointer

crimson plinth
#

thanks. I'll have to think about that.

twin pond
#

The rule is that when you use & on a comptime-known value, the resulting pointer has infinite lifetime (whereas for a runtime-known value, as you correctly identifier, its lifetime is tied to the frame)

#

If you're ever not sure if something is comptime-known, you can always throw in a comptime keyword (in this case .vtable = comptime &.{ ... }); that'll make it compile error if it's not comptime-known