I am trying to solve a problem from r/dailyprogrammer and have run into a problem with borrowing a String as mutable.
I'm trying to see if a String has been "looped" around. Comparing "hello" to "llohe" would return true whereas "hello" to "oelhl" would not. My strategy was to double one string and see if it contains the other one:
fn main() {
let x = String::from("hello");
let mut y = String::from("llohe");
println!("{}", compare(x, &mut y));
}
fn compare(x: String, y: &mut String) -> bool {
y.push_str(y.as_str());
if y.contains(&x) {
true
} else {
false
}
}
error[E0502]: cannot borrow `*y` as mutable because it is also borrowed as immutable
--> src/main.rs:8:5
|
8 | y.push_str(y.as_str());
| ^^--------^-^^^^^^^^^^
| | | |
| | | immutable borrow occurs here
| | immutable borrow later used by call
| mutable borrow occurs here
I don't know where the heck I'm doing that. I am trying to become friends with the compiler, but it is quite prickly.