3 ms·
An example of a variable size Vec in a struct: My understanding is that technically the Vec object itself is fixed size under the hood (a pointer and size fiel
by gnode 9y ago
An example of a variable size Vec in a struct:
My understanding is that technically the Vec object itself is fixed size under the hood (a pointer and size field), but as far as I can tell, this is what you're after. It needs no references or boxes.
https://play.rust-lang.org/?gist=8d88b83daa2f389892bfa95c8dbd9423&version=stable https://play.rust-lang.org/?gist=8d88b83daa2f389892bfa95c8db...
extern crate rand;
use rand::Rng;
#[derive(Debug)]
struct MyStruct {
v: Vec<u32>
}
impl MyStruct {
pub fn new() -> MyStruct {
let mut rng = rand::thread_rng();
let n = rng.gen_range( 4, 10 );
MyStruct {
v: rng.gen_iter().take( n ).collect()
}
}
}
fn main() {
let ms = MyStruct::new();
println!( "{:?}", ms );
}