The function should accept a word that can be &str or String. Then, I want to allocate a new String for the modified word during formatting if it's needed and return the value as a Cow.
fn format_word<'a>(&self, w: impl AsRef<str> + 'a) -> Cow<'a, str> {
let w = w.as_ref();
let is_correct = w
.chars()
.all(|c| c.is_lowercase() && !self.ignore_chars.contains(c));
if is_correct {
Cow::Borrowed(w)
} else {
Cow::Owned(
w.chars()
.filter(|c| !self.ignore_chars.contains(c.clone()))
.collect::<String>()
.to_lowercase(),
)
}
}
But the compiler complaining about the following.
error[E0515]: cannot return value referencing function parameter `w`
|
165 | let w = w.as_ref();
| ---------- `w` is borrowed here
...
172 | Cow::Borrowed(w)
| ^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
Is it fixable?
I will leave the original and correct version of the function to maybe give you more context on what I'm trying to achieve.
fn format_word<'a>(&self, w: &'a str) -> Cow<'a, str> {
let is_correct = w
.chars()
.all(|c| c.is_lowercase() && !self.ignore_chars.contains(c));
if is_correct {
Cow::Borrowed(w)
} else {
Cow::Owned(
w.chars()
.filter(|c| !self.ignore_chars.contains(c.clone()))
.collect::<String>()
.to_lowercase(),
)
}
}
This works well, but only with &str and sometimes it isn't enough.