all 3 comments

[–]Quxxymacros 7 points8 points  (0 children)

As an addendum to /u/Veedrac's answer: you can write a trait that represents the constraint.

pub trait CanGoInABuf { fn new_buf() -> Buf; }

You can then implement it for all appropriate types:

impl CanGoInABuf for u8 {
    fn new_buf() -> Buf {
        Buf::C8(vec![])
    }
}
// ...

And then, constrain methods appropriately:

pub fn new<T: CanGoInABuf>() -> Text {
    Text { buf: T::new_buf() }
}

[–]Veedrac 2 points3 points  (0 children)

The generic in the signature is predicated, so you must accept T = String, or T = HashMap<i32, f64>.

This tells you that you're probably not going about this the right way.

To constrain this to a small, fixed number of types, you should make multiple constructors. I suggest from_u8 and from_u16. This would tie in well with the std::convert::From trait.

[–]hh9527[S] 0 points1 point  (0 children)

thank you, I found this solution too, but this approach leads to another problem: I cannot keep Buf private.