Hi all,
I'm trying to implement a trait (Strip
), that can delete chars from a &mut String based on a Pattern
.
I don't understand why my code compiles when the pattern is defined inside my trait method (example 1). An why it fails when my pattern is passed as a parameter of my trait method (example 2).
The compiler gives me the following error :
error[E0502]: cannot borrow `*data` as mutable because it is also borrowed as immutable
--> src/main.rs:18:13
|
15 | fn strip<P: Pattern<'a> + Copy>(&self, pattern: P, data: &'a mut String) {
| -- lifetime `'a` defined here
16 | while let Some(index) = data.find(pattern) {
| ------------------
| |
| immutable borrow occurs here
| argument requires that `*data` is borrowed for `'a`
17 | // The following line triggers a compile error
18 | data.remove(index);
| ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
There's some lifetime issues that I don't understand well and that I don't know how to fix.
#![feature(pattern)]
#![feature(in_band_lifetimes)]
use std::str::pattern::Pattern;
pub struct Foo {}
pub trait Strip {
fn strip<P: Pattern<'a> + Copy>(&self, pattern: P, data: &'a mut String);
}
impl Strip for Foo
{
// In this example I don't use the _pattern parameter
fn strip<P: Pattern<'a> + Copy>(&self, _pattern: P, data: &'a mut String) {
while let Some(index) = data.find(char::is_lowercase) {
data.remove(index);
}
}
}
fn main() {
let foo = Foo{};
let mut input = "AbCdEf".to_string();
foo.strip(char::is_lowercase, &mut input);
}
#![feature(pattern)]
#![feature(in_band_lifetimes)]
use std::str::pattern::Pattern;
pub struct Foo {}
pub trait Strip {
fn strip<P: Pattern<'a> + Copy>(&self, pattern: P, data: &'a mut String);
}
impl Strip for Foo
{
// In this example I'm using the pattern parameter
fn strip<P: Pattern<'a> + Copy>(&self, pattern: P, data: &'a mut String) {
while let Some(index) = data.find(pattern) {
// The following line triggers a compile error
data.remove(index);
}
}
}
fn main() {
let foo = Foo{};
let mut input = "AbCdEf".to_string();
foo.strip(char::is_lowercase, &mut input);
foo.strip(' ', &mut input);
}
Thank you for you help.