[英]How to delete values from an unsigned integer array in rust
I am trying to write a function that removes all occurrences of 1,2 and 3 from an array of unsigned integers.我正在尝试编写一个 function 从无符号整数数组中删除所有出现的 1,2 和 3。 I have used the retain method but the error I am getting is:
我使用了 retain 方法,但我得到的错误是:
rustc -o main main.rs
error[E0599]: no method named `retain` found for array `[u32; 7]` in the current scope
--> main.rs:3:5
|
3 | arr.retain(|&x| x != 1 || x != 2 || x != 3);
| ^^^^^^ method not found in `[u32; 7]`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`.
compiler exit status 1
This is what I have so far:这是我到目前为止所拥有的:
fn remover(arr:[u32;7]){
arr.retain(|&x| x != 1 || x != 2 || x != 3);
println!("{:?}",arr);
}
fn main() {
let v = [1,2,3,4,5,6,7];
remover(v);
}
Why can I not use the retain method?为什么我不能使用retain方法? Is there something else I can use?
还有什么我可以使用的吗?
An array has a fixed size ( [u32; 7]
will always have 7 elements), therefore it doesn't make sense to remove elements from it.数组具有固定大小(
[u32; 7]
将始终有 7 个元素),因此从中删除元素是没有意义的。
If you want a dynamically sized sequence, you should use Vec
, which does have aretain
method .如果你想要一个动态大小的序列,你应该使用
Vec
,它确实有一个retain
方法。
Or you could keep an array and use Iterator::filter
, if you don't actually need to update the source.或者,如果您实际上不需要更新源,则可以保留一个数组并使用
Iterator::filter
。
Arrays are statically sized in Rust, its size is part of the type. Arrays 在 Rust 中是静态大小的,它的大小是类型的一部分。
[u32; 7]
[u32; 7]
defines the array to hold exactly 7 u32
values. [u32; 7]
将数组定义为恰好包含 7 个u32
值。
If you want to have a dynamic number of values, you will need to use Vec<u32>
instead, ie declare v
as vec,[1,2,3,4,5,6,7]
and make your remover()
take Vec<u32>
instead.如果您想要动态数量的值,则需要使用
Vec<u32>
,即将v
声明为vec,[1,2,3,4,5,6,7]
并让您的remover()
取取而代之的Vec<u32>
。
An alternative solution, you can proceed to filter to a slice of your array.另一种解决方案是,您可以继续过滤到数组的一部分。 By doing you do not duplicate data, avoiding creating a new vector.
通过这样做,您不会重复数据,避免创建新向量。
fn main()
{
let v = [1,2,3,4,5,6,7];
let v_filtered = &v
.iter()
.filter(|&&x| x != 1 && x != 2 && x != 3)
.inspect(|&&x| println!("retained {}", x))
.collect::<Vec<_>>();
dbg!(v);
dbg!(v_filtered);
}
Pay attention, I changed the predicate of my filter.注意,我改变了过滤器的谓词。 Here is my playground
这里是我的游乐场
You can remove debugging info and iteration inspection value for the release version.您可以删除发布版本的调试信息和迭代检查值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.