3 ms·
Zig compiles everything as one large compilation unit, so inlining isn't much of an issue there. If you want to have private fields, there's a couple ways to go
by TUSF 4y ago
Zig compiles everything as one large compilation unit, so inlining isn't much of an issue there. If you want to have private fields, there's a couple ways to go about it. You can make use of opaque types, of course, or you could use @fieldParentPtr to hide your private implementation from the API.
Something like so:
/// The internal implementation of this type.
const PrivateType = struct {
// Private fields.
field_a: u32,
field_b: bool,
// Public object exposed
public: PublicType,
// private functions here.
}
/// This gets exposed to the public API
pub const PublicType = struct {
// Public fields.
field_a: u32,
// Public functions here.
pub fn create(alloc: Allocator) !*PublicType {
var priv = try alloc.create(PrivateType);
return &priv.public;
}
/// Flips internal field b.
pub fn flip(p: *PublicType) void {
// Grabs the PrivateType that contains this PublicType as a field.
const self = @fieldParentPtr(PrivateType, "public", p);
self.*.field_b = !self.*.field_b;
}
}