I have a vector datawith an unknown size at compile time. I want to create a new vector of exact size. These options do not work:
data
let size = data.len(); let mut try1: Vec<u32> = vec![0 .. size]; //ah, you need compile-time constant let mut try2: Vec<u32> = Vec::new(size); //ah, there is no constructors with arguments
I'm a little upset - in the Rust API, book, link or rustbyexample.com there is no information on how to make such a simple basic task with a vector. This solution works, but I don’t think it’s good to do it, it’s strange to create elements one by one, and I don’t need any exact values for the elements:
let mut temp: Vec<u32> = range(0u32, data.len() as u32).collect();
You can use the constructor Vec::with_capacity()followed by an unsafe call set_len():
Vec::with_capacity()
set_len()
let n = 128; let v: Vec<u32> = Vec::with_capacity(n); unsafe { v.set_len(n); } v[12] = 64; // won't panic
, "" . , , Copy ( , , ).
Copy
- . , , ; [0, 1, 2, …, size - 1], :
[0, 1, 2, …, size - 1]
let x = (0..size).collect::<Vec<_>>();
(range(0, size) (0..size), range .)
range(0, size)
(0..size)
range
, :
let x = std::iter::repeat(0).take(size).collect::<Vec<_>>();
, , Vec::with_capacity(capacity) - , .
Vec::with_capacity(capacity)
, .