我的这个片段没有通过借阅检查器:
use std::collections::HashMap;
enum Error {
FunctionNotFound,
}
#[derive(Copy, Clone)]
struct Function<'a> {
name: &'a str,
code: &'a [u32],
}
struct Context<'a> {
program: HashMap<&'a str, Function<'a>>,
call_stack: Vec<Function<'a>>,
}
impl<'a> Context<'a> {
fn get_function(&'a mut self, fun_name: &'a str) -> Result<Function<'a>, Error> {
self.program
.get(fun_name)
.map(|f| *f)
.ok_or(Error::FunctionNotFound)
}
fn call(&'a mut self, fun_name: &'a str) -> Result<(), Error> {
let fun = try!(self.get_function(fun_name));
self.call_stack.push(fun);
Ok(())
}
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
error[E0499]: cannot borrow `self.call_stack` as mutable more than …Run Code Online (Sandbox Code Playgroud) 我有这段代码:
#[derive(Debug)]
struct Foo<'a> {
x: &'a i32,
}
impl<'a> Foo<'a> {
fn set(&mut self, r: &'a i32) {
self.x = r;
}
}
fn main() {
let v = 5;
let w = 7;
let mut f = Foo { x: &v };
println!("f is {:?}", f);
f.set(&w);
println!("now f is {:?}", f);
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,在第一次借用值时v,'astruct声明中的泛型生命周期参数将填充值的生命周期v.这意味着生成的Foo对象的'a寿命不得超过此生命周期,或者v必须至少与Foo对象一样长.
在对方法的调用中set,impl使用块上的生命周期参数,并在方法签名中w填充值的生命周期'a …
我有以下代码:
struct Baz {
x: usize,
y: usize,
}
struct Bar {
baz: Baz,
}
impl Bar {
fn get_baz_mut(&mut self) -> &mut Baz {
&mut self.baz
}
}
struct Foo {
bar: Bar,
}
impl Foo {
fn foo(&mut self) -> Option<&mut Baz> {
for i in 0..4 {
let baz = self.bar.get_baz_mut();
if baz.x == 0 {
return Some(baz);
}
}
None
}
}
Run Code Online (Sandbox Code Playgroud)
它无法编译:
error[E0499]: cannot borrow `self.bar` as mutable more than once at a time …Run Code Online (Sandbox Code Playgroud)