This is a maybe-RFC, because I’m not even sure if the idea is actually as interesting as it seems to me.
Idea
To create an As trait, which represents possibility of casting with as keyword:
trait As<T> {
fn as(self) -> T;
}
By default the trait is defined in stdlib for all types that can be casted with an as keyword.
Motivation
Currently there’s no way to define a type that is castable to another one. One can’t write a generic structure that holds anything castable to u32. Or a function that accepts fn item that can be casted to a specific fn pointer.
Another thing is elevation of as keyword to a fully functional operator, that can be defined by user for types, same as +, [] and ?. Automatic coercion between custom types becomes a thing.
This potentially makes the experimental CoerceUnsized trait fully covered and obsolete.
The wrapper is going to work in non-generic case, but it’s a workaround adding custom cruft to code. The new trait is clean, global and generic solution. At least it’s supposed to be.
Because coherence. (std::num::Wrapping isn't fundamental.)
It's legal to
impl From<i32> for Foo { ... }
But using wrapping you get
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/lib.rs:6:1
|
6 | impl From<Wrapping<i32>> for Wrapping<Foo> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate