The desired behaviour is if you can cut off 4 bytes cut and return 4 bytes, else if you can cut off 2 bytes cut and return 2 bytes, else return an error.
The methods cut
, cut_alternative
and cut_alternative_1
try to achieve this. The compiler error messages are listed below.
Why do all of these example methods fail to compile? In cut_alternative_1
the borrows are separated from each other while the error message is the same.
Can you give a workaround?
struct StrWrapper<'s> {
content: &'s str,
}
impl<'s> StrWrapper<'s> {
fn cut(&mut self) -> Result<&str, ()> {
self.cut4()
.or(self.cut2())
}
fn cut_alternative(&mut self) -> Result<&str, ()> {
if let Ok(part) = self.cut4() {
Ok(part)
} else if let Ok(part) = self.cut2() {
Ok(part)
} else {
Err(())
}
}
fn cut_alternative_1(&'s mut self) -> Result<&'s str, ()> {
{
let part = self.cut4();
if part.is_ok() {
return part;
}
}
{
let part = self.cut2();
if part.is_ok() {
return part;
}
}
Err(())
}
fn cut2(&mut self) -> Result<&str, ()> {
if self.content.len() >= 2 {
let part = &self.content[..2];
self.content = &self.content[2..];
Ok(part)
} else {
Err(())
}
}
fn cut4(&mut self) -> Result<&str, ()> {
if self.content.len() >= 4 {
let part = &self.content[..4];
self.content = &self.content[4..];
Ok(part)
} else {
Err(())
}
}
}
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/parser.rs:210:17
|
208 | fn cut(&mut self) -> Result<&str, ()> {
| - let's call the lifetime of this reference `'1`
209 | self.cut4()
| ----
| |
| _________first mutable borrow occurs here
| |
210 | | .or(self.cut2())
| |_________________^^^^_______- returning this value requires that `*self` is borrowed for `'1`
| |
| second mutable borrow occurs here
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/parser.rs:216:34
|
213 | fn cut_alternative(&mut self) -> Result<&str, ()> {
| - let's call the lifetime of this reference `'1`
214 | if let Ok(part) = self.cut4() {
| ---- first mutable borrow occurs here
215 | Ok(part)
| -------- returning this value requires that `*self` is borrowed for `'1`
216 | } else if let Ok(part) = self.cut2() {
| ^^^^ second mutable borrow occurs here
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/parser.rs:230:24
|
207 | impl<'s> StrWrapper<'s> {
| -- lifetime `'s` defined here
...
224 | let part = self.cut4();
| ---- first mutable borrow occurs here
225 | if part.is_ok() {
226 | return part;
| ---- returning this value requires that `*self` is borrowed for `'s`
...
230 | let part = self.cut2();
| ^^^^ second mutable borrow occurs here
@Shepmaster commented a link to a similar question: Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in?
This question differs in two ways:
- There are multiple mutable borrows instead of one unmutable and one mutable borrow.
- I am unable to apply the workarounds in the answer to this problem right now. A workaround would be much appreciated.