Extension trait or bare functions?

In the zerocopy crate, we're adding the ability to extend Vecs 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);

I find extension traits that are only ever implemented for one type pretty ugly. They also require importing the extension trait, which is non-obvious. So I would cast my vote in favor of the free function approach.

1 Like

In this case I think I agree that an extension trait on Vec might be a little confusing so free functions would probably be better.

With traits you could use the fully qualified form to prevent future breakage:

<Vec<T> as VecExt<T>>::extend_zeroed(&mut myvec, 3);

But then that's even more verbose than the bare functions options, so... One step forward, two backward.

1 Like

OK thanks for the advice, folks! I've decided to stick to bare functions.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.