gpt4 book ai didi

rust - `` 和 `where T: Trait` 有什么区别?

转载 作者:行者123 更新时间:2023-11-29 07:44:29 24 4
gpt4 key购买 nike

the docs对于 Send 特性,我看到了两者

impl<T> Send for LinkedList<T> 
where
T: Send,

impl<T: Send> Send for LinkedList<T>

这两种语法之间有什么区别,如果我为自己的特征编写 impl 声明,它会如何影响我的代码?

最佳答案

where 中定义的特征边界子句是内联声明的特征边界的超集。内联样式存在于 where 之前条款; where子句是 introduced in RFC 135 :

Add where clauses, which provide a more expressive means ofspecifying trait parameter bounds. [...] The existing bounds notationwould remain as syntactic sugar for where clauses.

Here is a list of limitations with the current bounds syntax that areovercome with the where syntax:

  • It cannot express bounds on anything other than type parameters. Therefore, if you have a function generic in T, you can writeT:MyTrait to declare that T must implement MyTrait, but you can'twrite Option<T> : MyTrait or (int, T) : MyTrait. These forms are lesscommonly required but still important.

  • It does not work well with associated types. This is because there is no space to specify the value of an associated type. Otherlanguages use where clauses (or something analogous) for this purpose.

  • It's just plain hard to read. Experience has shown that as the number of bounds grows, the current syntax becomes hard to read andformat.

从那时起,您还可以在 for <'a> ... 中使用 higher-ranked trait bounds ( where )子句:

fn foo<T, U>()
where
// higher-ranked trait bounds
for<'a> T: SomethingElse<'a>,
// Bound not directly on the generic type
i32: From<U>,
T: Iterator,
// Bound on an associated type
T::Item: Clone,
// Just really long
U: ReallyLong + AnotherReallyLong + WowReallyLong,
{}

如果内联特征边界可以满足您的需求,那么对您的代码没有任何影响。如果你需要额外的权力,只有 where启用,那么你需要使用where .

另见:


我的个人风格是总是使用where形式。具有单一形状也更容易git diff添加新边界对我来说值得额外的代码行。

关于rust - `<T: Trait>` 和 `where T: Trait` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46793494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com