如何给 impl 特征起别名?

How to alias an impl trait?

我有很多具有以下类型签名的函数:

fn f() -> impl Fn(u32) -> u32 { 
    |x: u32| x 
}

如何给 Fn(u32) -> u32 起一个名字,这样我就不必重复了?虽然我可以做到 type X = Fn(u32) -> u32;,但 Rust 不会让我使用它,因为它是一种类型而不是特征。我必须等待 trait_alias 还是可以做其他事情?

你完全正确。 impl X 要求 X 成为特征,并且在 trait aliases 登陆之前不可能拥有适当的特征别名。当发生这种情况时,您将能够这样做:

#![feature(trait_alias)]

trait X = Fn(u32) -> u32;

fn f() -> impl X {
    |x: u32| x
}

(playground)


或者,当 Permit impl Trait in type aliases 登陆时,您可以将 impl trait 设为 type 别名。不过,这略有不同。当我们使用 type X = impl Trait 作为别名时,编译器将确保 X 的每次使用实际上都是相同的具体类型。这意味着,在您的情况下,您将无法将它与多个不同的闭包一起使用,因为每个闭包都有自己独特的类型。

#![feature(type_alias_impl_trait)]

type X = impl Fn(u32) -> u32;

fn f() -> X {
    |x: u32| x
}

(playground)

但是,无法编译

#![feature(type_alias_impl_trait)]

type X = impl Fn(u32) -> u32;

fn f() -> X {
    |x: u32| x
}

// Even a closure with exactly the same form has a different type.
fn g() -> X {
    |x: u32| x
}

错误是

error: concrete type differs from previous defining opaque type use
  --> src/lib.rs:10:1
   |
10 | / fn g() -> X {
11 | |     |x: u32| x
12 | | }
   | |_^ expected `[closure@src/lib.rs:7:5: 7:15]`, got `[closure@src/lib.rs:11:5: 11:15]`
   |
note: previous use here
  --> src/lib.rs:6:1
   |
6  | / fn f() -> X {
7  | |     |x: u32| x
8  | | }
   | |_^

(playground)

这与 trait 别名形成对比,后者允许在每个函数返回 impl TraitAlias 时使用不同的具体类型。有关更多信息,请参阅引入 this syntax and existential types in general 的 RFC。


在这两个功能中的一个出现之前,您可以获得与 trait 别名类似的行为,本质上是一种 hack。这个想法是制作一个新的特征,它本质上等同于原始特征,但名称更短。

// This trait is local to this crate,
// so we can implement it on any type we want.
trait ShortName: Fn(u32) -> u32 {}

// So let's go ahead and implement `ShortName`
// on any type that implements `Fn(u32) -> u32`.
impl<T: Fn(u32) -> u32> ShortName for T {}

// We can use `ShortName` to alias `Fn(u32) -> u32`.
fn f() -> impl ShortName {
    |x: u32| x
}

// Moreover, the result of that can be used in places
// that expect `Fn(u32) -> u32`.
fn g<T: Fn(u32) -> u32>(x: &T) -> u32 {
    x(6_u32)
}

fn main() {
    // We only know that `x` implements `ShortName`,
    let x = f();
    // But we can still use `x` in `g`,
    // which expects an `Fn(u32) -> u32` argument
    let _ = g(&x);
}

(playground)