66
Don't write Rust like it's Java
(jgayfer.com)
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Credits
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.