struct StructNothing;
impl<'a> StructNothing {
fn nothing(&'a mut self) -> () {}
fn twice_nothing(&'a mut self) -> () {
self.nothing();
self.nothing();
}
}
然而,如果我们试图将其打包成一个特质,它会失败:
pub trait TraitNothing<'a> {
fn nothing(&'a mut self) -> () {}
fn twice_nothing(&'a mut self) -> () {
self.nothing();
self.nothing();
}
}
这给我们带来了:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/lib.rs:6:9
|
1 | pub trait TraitNothing<'a> {
| -- lifetime `'a` defined here
...
5 | self.nothing();
| --------------
| |
| first mutable borrow occurs here
| argument requires that `*self` is borrowed for `'a`
6 | self.nothing();
| ^^^^ second mutable borrow occurs here
- 为什么第一种版本被允许,而第二种版本被禁止?
- 有没有办法说服编译器第二个版本是可以的?
背景和动机
像rust-csv
这样的库希望支持流式、零拷贝解析,因为根据基准测试,它比分配内存快25到50倍。但 Rust 的内置 Iterator
特性不能用于此,因为无法实现collect()
方法。 目标是定义一个 StreamingIterator
特性,可由 rust-csv
和几个类似的库共享,但迄今为止,每次尝试实现它都遇到了上述问题。
fn nothing(&'a mut self)
更改为fn nothing(&mut self)
可以解决这个问题。考虑到你的函数没有返回值,你真的需要这个生命周期指定符吗?然而,这看起来确实是一个bug。 - Levanstrait StreamingIterator<T<'*>> { fn next<'a>(&'a mut self) -> T<'a>; }
。不过目前我们不能准确地表达这个意思。 - huon