this post was submitted on 08 Oct 2023
66 points (92.3% liked)

Rust

6041 readers
22 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 5 points 1 year ago (1 children)

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…

[–] [email protected] 1 points 1 year ago (1 children)

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.

[–] [email protected] 1 points 1 year ago

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 the any type in TypeScript), but the compiler doesn't allow ducktyping anyways.