I'm trying to write a simple function to escape HTML text (yes I know there are crates). Something like this:
fn escape(s: &str) -> String {
s.chars().flat_map(|c| {
match c {
'<' => ['&', 'l', 't'].iter(),
'>' => ['&', 'g', 't'].iter(),
'"' => ['&', 'q', 'u', 'o', 't'].iter(),
'\'' => ['&', 'a', 'p', 'o', 's'].iter(),
'&' => ['&', 'a', 'm', 'p'].iter(),
c => std::iter::once(c),
}
}).collect()
}
But it doesn't work, because the return types are different for the different arms:
expected struct `std::slice::Iter`, found struct `std::iter::Once`
I've tried many many things, but everything I try has some small problem:
- You can't do
"<".chars()
andc.chars()
becausechar
doesn't implementchars()
. - You can't do
[c].iter()
becausec
is on the stack anditer()
only keeps a reference to it - I couldn't work out how to move stuff into the iterator (I guess you probably can't).
Is there some sensible solution (that doesn't involve .to_string()
).