impl Trait
s can be used as function arguments。是否有与性状约束这和通用功能之间的区别是什么?
trait Foo {}
fn func1(_: impl Foo) {}
fn func2<T: Foo>(_: T) {}
impl Trait
s作为函数参数被脱到一个匿名的泛型参数。见RFC,其中说:
展开
impl Trait
允许使用的参数,它的行为就像一个匿名的泛型参数。
还有在RFC一个例子:
// These two are equivalent
fn map<U>(self, f: impl FnOnce(T) -> U) -> Option<U>
fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U
然而,不同的是,impl Trait
参数不能有自己的类型明确指定:
fn foo<T: Trait>(t: T)
fn bar(t: impl Trait)
foo::<u32>(0) // this is allowed
bar::<u32>(0) // this is not
该Motivation for expanding to argument position部分解释了为什么在现有的功能已添加额外的语法。总之,它是具有函数返回的位置,从而提高学习能力,并提高工效类似的语法impl
特质。
都产生相同的组件,至少具有下列简单的测试案例:
trait Foo {}
struct Bar;
impl Foo for Bar {}
fn func1(_: impl Foo) {}
fn func2<T: Foo>(_: T) {}
fn main() {
let x = Bar;
let y = func1(x); // or func2(x);
}