Rust provides a few ways to store a collection of elements inside a user-defined struct. The struct can be given a custom lifetime specifier, and a reference to a slice:
struct Foo<'a> {
elements: &'a [i32]
}
impl<'a> Foo<'a> {
fn new(elements: &'a [i32]) -> Foo<'a> {
Foo { elements: elements }
}
}
Or it can be given a Vec
object:
struct Bar {
elements: Vec<i32>
}
impl Bar {
fn new(elements: Vec<i32>) -> Bar {
Bar { elements: elements }
}
}
What are the major differences between these two approaches?
- Will using a
Vec
force the language to copy memory whenever I callBar::new(vec![1, 2, 3, 4, 5])
? - Will the contents of
Vec
be implicitly destroyed when the ownerBar
goes out of scope? - Are there any dangers associated with passing a slice in by reference if it's used outside of the struct that it's being passed to?