我有两个HashSet<u16>s,我想实现a = a U b. 如果可能,我想使用HashSet::union而不是循环或其他调整。
我尝试了以下方法:
use std::collections::HashSet;
let mut a: HashSet<u16> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<u16> = [7, 8, 9].iter().cloned().collect();
// I can build a union object that contains &u16
let union: HashSet<&u16> = a.union(&b).collect();
// But I can't store the union into a
a = a.union(&b).collect(); // -> compile error
// of course I can do
for x in &b {
a.insert(*x);
}
// but I wonder if union …Run Code Online (Sandbox Code Playgroud) anyPython的标准库中有一个非常方便的函数,该函数允许检查给定可迭代项中是否有任何项验证了某种条件。
my_list = [1, 3, 4, 5, 8]
# using any
four_is_present = any(elem == 4 for elem in my_list)
# is equivalent to
four_is_present = False
for elem in my_list:
if elem == 4:
four_is_present = True
break
Run Code Online (Sandbox Code Playgroud)
我想知道Rust中是否有等效的语法糖,或者我是否必须选择“更长”的表达方式。
我可以使用resize,但似乎有点过头了,因为我不需要调整向量的大小,只需修改其值即可。不能选择使用新变量,因为此向量实际上是结构中的一个字段。
我猜这resize是有效的,可能是我的问题的答案,但是它的名称并不具有在不更改大小的情况下重置值的含义。
在C语言中,我将使用memset(反对realloc)。
我的问题的插图:
let my_vec_size = 42;
let mut my_vec = Vec::new(); // 'my_vec' will always have a size of 42
my_vec.resize(my_vec_size, false); // Set the size to 42, and all values to false
// [ ... ] piece of code where the values in 'my_vec' will be modified, checked, etc ...
// now I need to reuse my_vec.
// Possibility A -> use resize again
my_vec.resize(my_vec_size, false);
// Possibility B …Run Code Online (Sandbox Code Playgroud)