Comment by continuational
9 hours ago
Do you really prefer this:
fn Maybe(comptime T: type) type {
return union(enum) {
value: T,
nothing,
const Self = @This();
pub fn just(the_val: T) Self { return .{ .value = the_val }; }
pub fn nothing() Self { return .nothing; }
}
}
Over this?
data Maybe a = Just a | Nothing
Optionals handle this in zig:
Write:
Read:
Sure, but this is an example from the article, and pertains to sum types in general, not just Maybe.
i dont think its generally a good idea to be making complex type generators like this in zig. just write the type out.
the annoyingness of the thing you tried to do in zig is a feature. its a "don't do this, you will confuse the reader" signal. as for optional, its a pattern that is so common that it's worth having builtin optimizations, for example @sizeOf(*T) == @sizeOf(usize) but @sizeOf(?*T) != @sizeOf(?usize). if optional were a general sum type you wouldn't be able to make these optimizations easily without extra information
3 replies →
Came to say this. Early in my career I really thought implementing Maybe in any language is necessary but not I know better. Use the idioms and don’t try to make every language something it’s not.
This looks like an example of a low level language vs a high level language (relatively speaking). The low level language makes a lot more of what is going on underneath explicit compared to the higher level language which abstracts that away for a common pattern. Presumably that explicitness allows for more control and/or flexibility. So apples to oranges?
I don't think so, where's the extra information in the Zig example?
In Rust, which is arguably also a low level language, it looks like this:
Low-level doesn’t mean more information, it means more explicit.
In Zig, that means being able to use the language itself to express type level computations. Instead of Rust’s an angle brackets and trait constraints and derive syntax. Or C++ templates.
Sure, it won’t beat a language with sugar for the exact thing you’re doing, but the whole point is that you’re a layer below the sugar and can do more.
Option<T> is trivial. But Tuple<N>? Parameterizing a struct by layout, AoS vs SoA? Compile time state machines? Parser generators? Serialization? These are likely where Zig would shine compared to the others.
3 replies →
My old memories of Guava in Java 6 have been triggered.