Given a &[u32]
I want to filter out the number 0
. This could be any number or any other rule or condition.
Here are a few versions that work, but I feel like this could be done simpler:
fn test(factors: &[u32]) {
let factors1 = factors
.iter()
.map(|&x| x as u32)
.filter(|x| *x != 0)
.collect::<Vec<u32>>();
let factors1 = factors
.iter()
.map(|&x| x as u32)
.filter(|&x| x != 0)
.collect::<Vec<u32>>();
let factors2 = factors
.iter()
.filter(|x| **x != 0)
.collect::<Vec<&u32>>();
let factors3 = factors
.iter()
.filter(|&&x| x != 0)
.collect::<Vec<&u32>>();
}
I was expecting something simpler like this (which doesn't work):
let factors4 = factors.iter().filter(|x| x != 0).collect();
Things that would be helpful are:
- Is it possible to clone or convert a
&u32
tou32
? - Is there a way to clone a
&[u32]
to[u32]
?