Hi,
The documentation of set_len(&mut self, new_len: usize)
say that:

new_len
must be less than or equal tocapacity()
.  The elements at
old_len..new_len
must be initialized.
If, the memory has been allocated but not initialized, then I set the len with set_len, and then I initialize each new element shouldn't it be safe? There is any UB in doing the below?
fn main() {
let mut rng = rand::thread_rng();
let mut g: Vec<u8> = Vec::with_capacity(100);
unsafe { g.set_len(100) };
for i in 0..100 {
let v: u8 = rng.gen();
g[i] = v;
}
dbg!(g.get(56));
}
The above and the below are equivalent?
fn main() {
let mut rng = rand::thread_rng();
let mut g: Vec<MaybeUninit<u8>> = unsafe {
vec![MaybeUninit::uninit().assume_init(); 100]
};
for elem in &mut g[..] {
let v: u8 = rng.gen();
*elem = MaybeUninit::new(v);
}
let g = unsafe { std::mem::transmute::<_, Vec<u8>>(g) };
dbg!(g[57]);
}
Are the aboves faster than the below?
fn main() {
let mut rng = rand::thread_rng();
let mut g = vec![0_u8;100];
for x in &mut g {
let v: u8 = rng.gen();
*x = v
}
dbg!(g[57]);
}
thanks!