什么是一个IMPL特征参数和泛型函数参数之间的区别是什么?

问题描述 投票:7回答:2

impl Traits can be used as function arguments。是否有与性状约束这和通用功能之间的区别是什么?

trait Foo {}

fn func1(_: impl Foo) {}

fn func2<T: Foo>(_: T) {}
rust
2个回答
11
投票

impl Traits作为函数参数被脱到一个匿名的泛型参数。见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特质。


5
投票

都产生相同的组件,至少具有下列简单的测试案例:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.