给定一个&[u32],我想过滤掉数字0。这可以是任何数字或任何其他规则或条件。
以下是几个可以工作的版本,但我觉得这可以做得更简单:
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>>();
}我还以为会有更简单的事情(这是行不通的):
let factors4 = factors.iter().filter(|x| x != 0).collect();会有帮助的事情有:
是否有可能克隆或将一个u32
[u32]
--有一种将&[u32]克隆到[u32]的方法
发布于 2019-11-04 00:37:37
let factors4: Vec<u32> = factors
.iter()
.copied()
.filter(|&x| x != 0)
.collect();发布于 2019-11-04 12:59:58
您可以在一个步骤中使用filter_map来实现filter和map。
fn make_vec_of_nonzero(factors: &[u32]) -> Vec<u32> {
factors
.iter()
.filter_map(|&x| if x == 0 { None } else { Some(x) })
.collect()
}https://stackoverflow.com/questions/58685861
复制相似问题