Cześć, uczę się Rusta i próbuję poprawnie użyć parametru czasu życia. Poniższa funkcja i wywołanie działały prawidłowo, zanim nie dodałem parametrów czasu życia:
fn reading<'a>(input : &mut dyn Read, tr : &'a mut TermReader<'a>) {
let mut buff : [u8;10] = [0;10];
while match input.read(&mut buff) {
Ok(len) => { tr.accept(&buff[0..len]) },
Err(e) => {
println!("ERROR: {}", e);
false
}
} {}
}
wywołanie:
let mut tr = TermReader::new(initial_keys, Some(KeyAction::Action(ac_elsekey)));
reading(&mut input, &mut tr);
println!("{}", tr.args.join(","));
Po dodaniu parametru czasu życia otrzymuję następujący komunikat:
error[E0499]: cannot borrow `*tr` as mutable more than once at a time
--> src/main.rs:125:22
|
121 | fn reading<'a>(input : &mut dyn Read, tr : &'a mut TermReader<'a>) {
| -- lifetime `'a` defined here
...
125 | Ok(len) => { tr.accept(&buff[0..len]) },
| ^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `*tr` was mutably borrowed here in the previous iteration of the loop
| argument requires that `*tr` is borrowed for `'a`
error[E0502]: cannot borrow `tr.args` as immutable because it is also borrowed as mutable
--> src/main.rs:201:20
|
200 | reading(&mut input, &mut tr);
| ------- mutable borrow occurs here
201 | println!("{}", tr.args.join(","));
| ^^^^^^^^^^^^^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
Co robię nie tak? Dlatego bez lifetime'a było ok, a teraz nie jest? Jak to naprawić?
'a
przykuwa ekstra uwagę, a nie zawsze jest to potrzebne 😁