How to implement a one-line Builder pattern in Zig when structs default to const?

a value not assigned to a variable is temporary, and taking a pointer to a temporary will always be const
this lets zig do more optimisations

a solution would be

var lw = ListWrapper.init(allocator);
lw.append('H').append('E').append('L').append('L').append('O').print();

some notes

  • ArrayList has appendSlice function, to append multiple elements at a time
  • toOwnedSlice can return an error
  • not sure why print takes ownership of the ArrayList slice, you can access the items with .items, it makes no sense for print to free the slice, anyone would be surprised by that behaviour
  • instead you should have a deinit function to clean up the resources instead of doing it in print
  • ArrayList stores the allocator, if you need to store it for some reason use ArrayListUnmanaged, same api as ArrayList except you pass an allocator to functions that need it

this isnt a builder pattern this is just function chaining

a builder pattern is this

var builder = Builder.init();
builder.stuff();
builder.moreStuff();
const stuff = builder.build();

Builders often do allow function chaining, but they are different is my point

if you have any questions ask :3

5 Likes