A struct is defined as:
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[..]
}
}
The problem is:
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?
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.
No, your requirements are 100% completely impossible in safe Rust.
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.
You can "render a view" of the
HashSet
if you can store aVec
and the method is&mut self
:You could return a
Cow
which would be either borrowed or owned:You could return an iterator over the values:
There's possibly a crate that uses a tightly-packed
Vec
as its backing storage, which could then be exposed as a slice.That is impossible in simple (basic) ways.
That's possible with
Box
,mut static
but I recommend to modify your trait and return something like in following example:You can use
AsRef<[T]>
instead of&[usize]
in your trait. Or simply return an iterator.This is only two ways from many.