this post was submitted on 08 Oct 2023
65 points (92.2% liked)
Rust
6117 readers
3 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
I recently caught myself trying to do traits in an OOP language. Failed spectacularly of course.
But it would be so much easier to read…
Depending on your language, your closest analogue is going to be interfaces. C# even has a where clause where you can restrict a generic type such that any type substituted must implements one or more interfaces. You can get quite a bit of trait like working there, from the function input side of stuff.
The biggest problem is, you can't implement an interface for a type unless you have access to the type. So you'd have to really on wrapping types you don't own to apply trait like interfaces to it.
And then there's minor issues like, no such thing as associated types, or being able to specify constants in a definition. But you can usually work around that in a less nice way.
In my case, it was in Dart. Dart allows extending existing classes with new methods, but unfortunately this doesn't allow implementing abstract mixins (which is the equivalent of Rust's trait) on other types. Dart is in this weird middle where it's not really strictly typed (it has
dynamic
, which is like theany
type in TypeScript), but the compiler doesn't allow ducktyping anyways.