问题描述
结构定义为:
struct Node {
set: HashSet<usize>,
// other fields omitted
}
我必须实现特征(兼容性问题)的功能,该特征需要将集合中的所有元素作为切片返回.
I have to implement a function for a trait (compatibility issues) which needs to return all elements in the set as a slice.
我知道以下功能无法正常工作:
I am aware of something like the following function won't work:
impl Node {
pub fn set_slice(&self) -> &[usize] {
let elems: Vec<_> = self.set.iter().cloned().collect();
&elems[..]
}
}
问题是:
error[E0597]: `elems` does not live long enough
--> src/main.rs:11:10
|
11 | &elems[..]
| ^^^^^ borrowed value does not live long enough
12 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 9:5...
--> src/main.rs:9:5
|
9 | / pub fn set_slice(&self) -> &[usize] {
10 | | let elems: Vec<_> = self.set.iter().cloned().collect();
11 | | &elems[..]
12 | | }
| |_____^
我知道这个要求听起来很奇怪.尽管我为什么要做这个,但有没有好的"方法来实现呢?
I know this requirement may sound strange. Despite why I have to do this, is there any 'good' way to achieve this?
如果可能的话,我想保留HashSet
容器以进行O(1)查找,并且我不想引入新的struct成员以节省内存.
If it is possible, I want keep the HashSet
container for a O(1) lookup, and I don't want to introduce new struct members in order to save memory.
推荐答案
不,在安全的Rust中,您的要求是100%完全不可能的.
No, your requirements are 100% completely impossible in safe Rust.
A HashSet
/HashMap
没有连续的数据收集,因此无法从中获取切片.
A HashSet
/ HashMap
do not have a contiguous collection of data, thus there's no way to get a slice from them.
如果您可以进行更改,则可以选择.
If you can change things, then you have options.
如果可以存储Vec
并且方法为&mut self
,则可以呈现" HashSet
的视图:
You can "render a view" of the HashSet
if you can store a Vec
and the method is &mut self
:
struct Node {
set: HashSet<usize>,
view: Vec<usize>,
// other fields omitted
}
impl Node {
pub fn set_slice(&mut self) -> &[usize] {
self.view.clear();
self.view.extend(self.set.iter().cloned());
&self.view
}
}
您可以返回借用或拥有的Cow
:
You could return a Cow
which would be either borrowed or owned:
use std::borrow::Cow;
impl Node {
pub fn set_slice(&self) -> Cow<[usize]> {
self.set.iter().cloned().collect::<Vec<_>>().into()
}
}
您可以在值上返回迭代器:
impl Node {
pub fn set_slice<'a>(&'a self) -> impl Iterator<Item = &'a usize> + 'a {
self.set.iter()
}
}
有一个可能 一个板条箱,它使用紧密包装的Vec
作为其包装支持存储,然后可以将其公开为切片.
There's possibly a crate that uses a tightly-packed Vec
as its backing storage, which could then be exposed as a slice.
这篇关于如何从HashSet形成切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!