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.