You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It seems to me this ought to compile, or at least it's not clear to me why it doesn't. The following code:
use std::collections::HashMap;use std::borrow::Cow;pubtypeCache = HashMap<i32,i32>;fncompute<'cache>(input:i32,cache:&'cache mutCache) -> Cow<'cache,i32>{ifletSome(cached) = cache.get(&input){returnCow::Borrowed(cached)}let result = input + 2;
cache.insert(input, result);Cow::Borrowed(&cache[&input])}fnmain(){}
Yields:
error[E0502]: cannot borrow `*cache` as mutable because it is also borrowed as immutable
--> src/lib.rs:12:5
|
6 | fn compute<'cache>(input: i32, cache: &'cache mut Cache) -> Cow<'cache, i32> {
| ------ lifetime `'cache` defined here
7 | if let Some(cached) = cache.get(&input) {
| ----- immutable borrow occurs here
8 | return Cow::Borrowed(cached);
| --------------------- returning this value requires that `*cache` is borrowed for `'cache`
...
12 | cache.insert(input, result);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
Obviously my actual code is more complicated than this (it computes multiple outputs in the same non-cached path, might not cache the input, etc), so using .entry() etc is not really an option.
What am I missing?
The text was updated successfully, but these errors were encountered:
It seems to me this ought to compile, or at least it's not clear to me why it doesn't. The following code:
Yields:
Obviously my actual code is more complicated than this (it computes multiple outputs in the same non-cached path, might not cache the input, etc), so using
.entry()
etc is not really an option.What am I missing?
The text was updated successfully, but these errors were encountered: