Your code seems sound, in principle, as demonstrated by the fact that the new in-development borrow checker polonius accepts it just fine.
The problem that the current borrow checker sees is that since you return v in one branch of the match, it things that v must live until the end of the function call, hence the vec must remain borrowed immutably for just as long.
Talking about workarounds, I’m not quite sure what the best approach is, yet, if you want to avoid unsafe code and checking the validity twice; I’ll update my answer if I find a decent approach I can’t think of a good way. I guess, you’ll just want to use the unsafe approach, because doing the conversion twice seems stupid.
Edit: For clarity, these approaches work but require unsafe or do the work twice:
fn get_cow_expensive(vec: &mut Vec<u8>) -> Cow<str> {
if std::str::from_utf8(&vec[..]).is_ok() {
Cow::Borrowed(std::str::from_utf8(&vec[..]).unwrap())
} else {
vec.push(0);
Cow::Owned(String::new())
}
}
fn get_cow_with_unsafe(vec: &mut Vec<u8>) -> Cow<str> {
if std::str::from_utf8(&vec[..]).is_ok() {
Cow::Borrowed(unsafe {std::str::from_utf8_unchecked(&vec[..])})
} else {
vec.push(0);
Cow::Owned(String::new())
}
}