The following code does not compile:
use std::borrow::Cow;
fn get_cow(vec: &mut Vec<u8>) -> Cow<str> {
match std::str::from_utf8(&vec[..]) {
Ok(v) => Cow::Borrowed(v),
_ => {
vec.push(0);
Cow::Owned(String::new())
}
}
}
fn main() {
println!("{:?}", get_cow(&mut Vec::new()));
}
and the compiler returns the following error message:
error[E0502]: cannot borrow `*vec` as mutable because it is also borrowed as immutable
--> src/main.rs:7:13
|
3 | fn get_cow(vec: &mut Vec<u8>) -> Cow<str> {
| - let's call the lifetime of this reference `'1`
4 | match std::str::from_utf8(&vec[..]) {
| --- immutable borrow occurs here
5 | Ok(v) => Cow::Borrowed(v),
| ---------------- returning this value requires that `*vec` is borrowed for `'1`
6 | _ => {
7 | vec.push(0);
| ^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground`
To learn more, run the command again with --verbose.
Since on the Ok
branch, we exit immediately, why does the borrow checker care that we are mutably borrowing on the Err
branch? Is there an alternative way of writing this code which has the same functionality?
Here's the link to the playground: Rust Playground.