Is there any idiomatic way to take the last N characters from String
(where "character" is meant as the thing yielded by String::chars
)? For now, I'm using the following:
let len = string.chars().count() - N;
string.drain(0..len).for_each(|_| {});
But this approach looks a little ugly.
Hyeonu
June 21, 2020, 5:23am
2
This code is wrong, and may panic on non-ascii string , since the .drain()
takes byte length not character count. Quick fix.
1 Like
You don't need to actually do anything with the drained items (the for_each()
). The items will be removed whenever the result is dropped.
By using something like let _ = string.drain(0..len)
, you can explicitly say "just remove these items and throw them away" .
2 Likes
Oops, thanks. I looked too fast on the docs and assumed the opposite.
Thanks, that definitely looks more clear.
system
Closed
September 19, 2020, 6:59am
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.