考虑一个函数
fn clear_non_empty<T>(collection: &mut Vec<T>) {
if !collection.is_empty() {
collection.clear()
}
}
它编译得很好,如果我试着把它推广到一些集合中
trait IsEmpty {
fn is_empty(&self) -> bool;
}
trait Clear {
fn clear(&mut self);
}
fn clear_non_empty<'a, Collection: Clear + IsEmpty>(collection: &'a mut Collection) {
if !collection.is_empty() {
collection.clear()
}
}
我也没有问题.但是如果我把特征改成
trait IsEmpty {
fn is_empty(self) -> bool;
}
trait Clear {
fn clear(self);
}
fn clear_non_empty<'a, Collection>(collection: &'a mut Collection)
where
&'a mut Collection: Clear,
&'a Collection: IsEmpty,
{
if !collection.is_empty() {
collection.clear()
}
}
我正在
error[E0502]: cannot borrow `*collection` as mutable because it is also borrowed as immutable
--> src/lib.rs:15:9
|
9 | fn clear_non_empty<'a, Collection>(collection: &'a mut Collection)
| -- lifetime `'a` defined here
...
14 | if !collection.is_empty() {
| ---------------------
| |
| immutable borrow occurs here
| argument requires that `*collection` is borrowed for `'a`
15 | collection.clear()
| ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
我不明白,为什么特征的方法接受了self
个引用,而特征的实现方法接受了self
个引用却没有?