[英]rust lifetime problem, why the first call not compile error?
#[derive(Debug)]
struct NumRef<'a>(&'a i32);
impl<'a> NumRef<'a> {
// my struct is generic over 'a so that means I need to annotate
// my self parameters with 'a too, right? (answer: no, not right)
fn some_method(&'a mut self) {}
}
fn main() {
let mut num_ref = NumRef(&5);
num_ref.some_method(); // mutably borrows num_ref for the rest of its lifetime
num_ref.some_method(); // compile error
println!("{:?}", num_ref); // also compile error
}
'a is should be 'static, num_ref's lifetime is shorter then 'static 'a 应该是 'static,num_ref 的生命周期比 'static 短
The problem is that you've told Rust that some_method
needs self
for 'a
.问题是你已经告诉 Rust
some_method
需要self
用于'a
。
But by definition 'a
lives for longer than the instance of NumRef.但根据定义
'a
的寿命比 NumRef 的实例长。
This means the only way to fulfill your requirement is to create a borrow which lasts for the entire lifetime of the instance, aka as soon as the method is called you're completely locked out.这意味着满足您的要求的唯一方法是创建一个持续整个实例生命周期的借用,也就是一旦调用该方法,您就被完全锁定了。
You can just remove the lifetime bound from the self
entirely:您可以完全从
self
中删除生命周期:
impl<'a> NumRef<'a> {
fn some_method(&mut self) {}
}
These lifetimes are essentially unrelated: here some_method
cares about NumRef
, not 'a
.这些生命周期本质上是无关的:这里
some_method
关心NumRef
,而不是'a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.