Within a function which takes in &str
and returns impl Iterator<Item = char>
, I am trying to convert the input to lowercase and then filter and map the characters of that lowered form. I have been stuck for some time with the following error while using str.to_lowercase()
:
--> src/lib.rs
|
| cipher
| _____^
| |_____|
| ||
| || .to_lowercase()
| ||_______________________- temporary value created here
| | .chars()
| | .filter(|c| c.is_alphanumeric() && c.is_ascii())
... |
| | }
| | })
| |___________^ returns a value referencing data owned by the current function
The function in its original form:
pub fn decode_to_iter(cipher: &str) -> impl Iterator<Item = char> {
cipher
.to_lowercase()
.chars()
.filter(|c| c.is_alphanumeric() && c.is_ascii())
.map(|c| {
if c.is_alphabetic() {
(((b'z' - (c as u8)) + b'a') as char)
} else {
c
}
})
}
I came across a couple of questions online asking very similar questions about how to return an owned value that's been transformed with .to_lowercase()
but none of the solutions posted work for me.
I am trying to avoid using &char
and stick with char
in my return type.
I've tried to use functions like .to_owned()
to take ownership of the reference but have come up empty-handed.
Ultimately, I was able to get my function to compile and pass my tests using char.to_ascii_lowercase()
. The working version of my function is:
pub fn decode_to_iter<'a>(cipher: &'a str) -> impl Iterator<Item = char> + 'a {
cipher
.chars()
.filter(|c| c.is_alphanumeric() && c.is_ascii())
.map(|c| {
if c.is_alphabetic() {
(((b'z' - (c.to_ascii_lowercase() as u8)) + b'a') as char)
} else {
c.to_ascii_lowercase()
}
})
}
One of the things that are confusing me the most is what the difference between the str.to_lowercase()
and char.to_ascii_lowercase()
is. The documentation for .to_ascii_lowercase()
under Primative Type Char shows:
pub fn to_ascii_lowercase(&self) -> char
while the documentation for .to_lowercase()
under Primative Type Str shows:
pub fn to_lowercase(&self) -> String
Unless I'm misunderstanding, both functions seem to return an owned value so I am unsure why only char.to_ascii_lowercase()
works.
I am wondering:
how to properly return an
Impl Iterator
value which uses.to_lowercase()
rather than.to_ascsii_lowercase()
?what the difference is between
char.to_lowercase()
andstr.to_ascii_lowercase()
?