|
|
|
|
|
by jmull
495 days ago
|
|
> But in non trivial cases, the parameter can be passed all over the place Like pretty much any parameter in any language? That's abstraction. Re jsonStringfy, that's a way for a type to control how its own instances are serialized as JSON. std.json.stringify doesn't depend on the details of a jsonStringfy implementation (nor a caller of std.json.stringify). A type being able to implement a method to customize how instances of the type are serialized is a common/typical feature of a lot of JSON serializers. |
|
It’s crappy abstraction. Why make every user of the interface figure out how to use it properly? And guess what functions are required and which are always available?
Rust traits seem like a strictly better tool here. You get exactly the same emitted code as anytype, but the expected interface is explicit and well documented. Any time a trait name appears, you can cmd+click the trait name and see what functions are parts of the trait. It’s clean and explicit.
And traits can also have associated types (eg for an error type). They can have default implementations of functions. You can store a trait object in a struct. And you can use &dyn Trait if you want dynamic dispatch instead of monomorphisation. If this article is anything to go by, Zig makes all of this stuff difficult to impossible.
Anytype only solves the problem for the compiler. Traits solve the problem for the compiler and the programmer at the same time.