3 ms·
I agree with you. I'd like to see Rust change to allow defining traits on foreign types, somehow. I've discussed this a number of times with folks on the Rust
by jcrites 3y ago
I agree with you. I'd like to see Rust change to allow defining traits on foreign types, somehow.
I've discussed this a number of times with folks on the Rust community Discord. There are unfortunately obstacles to making this happen. One obstacle is that if you implement a trait for a type, then that implementation applies to it everywhere, including in all other library code using the type. By implementing a trait you change its behavior in surprising and likely conflicting ways. Additionally, if you were to implement `Serialize` for some struct, then that would also directly conflict with the struct owner trying to do the same thing.
My proposed solution to this problem is to conceptualized trait implementations as something that can be `use`d. The basic idea is that, if I implement `Serialize` for `Foo` (and `Foo` comes from another namespace) then the type-trait implementation remains private to mine (or perhaps, private to my namespace). That's not how Rust works today, but I'd be curious whether it could work.
I realize this will create a new set of challenges. It will mean `Foo` comes with one set of behavior everywhere else, and another set of behavior in my namespaces where the trait is implemented for it. I don't know enough about Rust to foresee what kind of problems this would cause, but it seems tempting to explore. Usually the kinds of traits that you'd want to implement are not ones that will cause problems for other code.
- ithkuil 3y agoWhat if the author of the trait explicitly marks it to allow that?
- glandium 3y agoSometimes I just wish that it were possible to do something akin to "pub(crate) impl Trait for Type", that would a) only make the trait implemented for the type in the current crate b) possibly override any other impl of the trait for said type.
- erutuon 3y agoI can see the convenience of sort of importing implementations of traits into scope. One difficulty is that traits are used for core functionality, like dereferencing and comparison operators. It would be inconvenient to have to import the implementations to do these basic things and confusing if some commonly used types could have their basic behavior dramatically changed. Maybe that could be solved by choosing some traits that are more central and preventing them from being switched out by importation, so you couldn't for instance change what `==` does to a pair of `f64`s.