In the zerocopy crate, we're adding the ability to extend Vec
s with zero-initialized values (see fxbug.dev/555581 for details). We're not sure whether these should be exposed as bare functions (which accept a &mut Vec<T>
parameter) or as methods on a new extension trait (which extends Vec<T>
). Any thoughts on what the right thing to do in this case is?
In my estimation, the main tradeoff is that extension traits result in more natural-looking code (e.g., zerocopy::extend_vec_zeroed(&mut myvec, 3)
vs myvec.extend_zeroed(3)
), but they also introduce a stability hazard (if the standard library ever introduced a Vec::extend_zeroed
method, existing code would break). Perhaps there are other considerations as well.
Appendix: Full APIs
Bare Functions
pub fn extend_vec_zeroed<T: FromBytes>(v: &mut Vec<T>, additional: usize) { ... }
pub fn insert_vec_zeroed<T: FromBytes>(v: &mut Vec<T>, position: usize, additional: usize) { ... }
zerocopy::insert_vec_zeroed(&mut myvec, 10, 20);
Extension Trait
pub trait VecExt<T: FromBytes + Sized> {
fn extend_zeroed(&mut self, additional: usize) { ... }
fn insert_zeroed(&mut self, position: usize, additional: usize) { ... }
}
myvec.insert_zeroed(10, 20);