There was a proposal for the typeof
operator in the past. The reason of closure is
This is the kind of thing we really need to go through the new formal RFC process.
But for years people didn't talk about it.
Now it is 2018, the year to make impl Trait
available in an LTS version. But there are still limitations on this feature that it does not allow it to appear in some situations, including inside a trait implementation.
The RFC 2071 was introduced to remove those situations, but the part of this RFC that allows existential types inside traits is not even have a active PR right now.
In my opinion, RFC 2071 may not be a better solution than simply allow impl
in trait function return types AND have the typeof
operator available.
typeof
and impl Trait
can do what that existential type
can
The following
// existential types
existential type Adder: Fn(usize) -> usize;
fn adder(a: usize) -> Adder {
|b| a + b
}
can be expressed with typeof
as:
type Adder = typeof(adder(a:usize));
fn adder(a: usize) -> impl Fn(usize) -> usize {
|b| a + b
}
EDIT a previous version was naive and would not be able to compile.
and
// `impl Trait` in traits:
struct MyStruct;
impl Iterator for MyStruct {
// Here we can declare an associated type whose concrete type is hidden
// to other modules.
//
// External users only know that `Item` implements the `Debug` trait.
existential type Item: Debug;
fn next(&mut self) -> Option<Self::Item> {
Some("hello")
}
}
will become
// `impl Trait` in traits:
struct MyStruct;
impl Iterator for MyStruct {
type Item = typeof((s:&mut Self).next().unwrap());
fn next(&mut self) -> Option<Self::Item> {
Some("hello")
}
}
So at least, we should adjust RFC 2071 and add this as an alternative. Can anyone show me the workflow to add an alternative to the RFC?
In other language(s)
The above typeof
is inspired by C++ decltype
keyword.