Recycling vecs using transmute
⚓ Rust 📅 2026-02-18 👤 surdeus 👁️ 7Hmm, came across this (more general) idea:
fn recycle_vec<A, B>(mut v: Vec<A>) -> Vec<B> {
const {
use std::alloc::Layout;
let la = Layout::new::<A>();
let lb = Layout::new::<B>();
assert!(la.size() == lb.size(), "Size of types must match");
assert!(la.align() == lb.align(), "Alignment of types must match");
}
v.clear();
// SAFETY: vector cleared, no elements affected, layout equal
unsafe { std::mem::transmute(v) }
}
Artificial usage example:
let mut vec = Vec::with_capacity(10);
loop {
let s = String::from("a b c");
vec.extend(s.split(' '));
vec = recycle_vec(vec);
}
What do you think?
Maybe an extension trait will beneficial: There are other candidates, like HashMap etc. This problem occurs occasionally in different forms, for example: Please help me let me keep my allocation
5 posts - 3 participants
🏷️ Rust_feed