Rust's std lib: Why are methods like `unwrap` not implemented by a trait?

I was just looking at the source code of the rust standard library, where I noticed that the unwrap method for instance is not implemented using a trait, which seems pretty reasonable to do because it's used in both Option and Result. Is this because it's old code? Or maybe because there aren't a lot of use cases for such a trait other than the aforementioned ones?

Well, not having a trait is the normal answer in Rust. After all, there's not a trait for wrapping_add or len or such either.

That said, if that were to be on a trait, it'd maybe be on the unstable Try in std::ops - Rust, which has enough to make it work already.


Yes, but what would you gain by doing so? Traits don't exist l'art pour l'art; their reason to be is to abstract away different types in generic code.

Not once in my Rust programming career did I need to abstract over unwrap. Unwrapping is the exception rather than the norm, and as such, it's pretty much specific to the situation when you should reasonably call it. It's thus not really valuable as a trait method.


Not sure if this applies here, but using trait methods are a bit more tricky in regard to namespace.

All traits which are in scope will make all their methods available for all types which implement the respective trait. If two methods have the same name, it will complicate syntax, and if a trait is not in scope, you can't use the .method() syntax either.

This is why it can make sense to implement methods directly on a struct or enum instead of going through a trait. This might become different if "inherent" traits are added to the language. See also this post for some examples.

But even with inherent traits, using a trait will increase overall complexity for the implementor, so I guess outside std it's reasonable to only do it when it's worth to provide an abstract interface.

If there is a trait for unwrap(), maybe there could be an operator (like ! in other languages) that desugars to unwrap()?

Let's not re-open that can of worms, please. It's come up before. It simply doesn't carry its weight and it's not going to happen.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.