A bit of background: Rust makes a distinction between coercion and subtyping. Coercions only apply at the "top level" of a type -- so you can go from &&T
to &T
, but not Vec<&&T>
to Vec<&T>
. Subtyping comes in with lifetimes, and triggers at all levels: you can go from &[&'static T]
to &[&'a T]
.
Now, consider what it would take to allow coercions to apply deeply; in a case like Vec<&&T>
above, you would actually have to create a new vector, because you're changing the elements in a significant way. Even if we could give you the tools to tell Rust how to do this, it's not the kind of thing we would generally want to happen as part of an implicit coercion, I think.
However, there might be potential to apply coercions in more places than today, without applying them arbitrarily deeply. Here's how I would think of it:
- The
AsRef
proposal is about adding a new coercion based onAsRef
, which fits into our existing coercion story. - Separately, as a distinct ergonomics improvement, we should ask whether there are situations where we can apply coercions at the function level in general. It seems quite plausible -- it would effectively be sugar for writing a closure that simply calls the function (i.e.,
|x| f(x)
), which would apply coercions.
I'd suggest starting a separate thread on that extension, and linking to it from the Ergonomics Roadmap tracker.