suppose we have a wrapper type,这个类型约束了T必须实现 Debug

    1. struct Wrapper<T>
    2. where T: std::fmt::Debug
    3. {
    4. pub inner: T
    5. }

    假如有个方法将Wrapper作为参数传入

    1. // because Wrapper take T as generic type, so the method that
    2. // take Wrapper as parameter should also fulfil the constraint that
    3. // T must implement std::fmt::Debug, but actually we don't care
    4. fn take_wrapper<T>(w: Wrapper<T>) -> T
    5. where T:std::fmt::Debug {
    6. w.inner
    7. }

    take_wapper也必须加上这个约束,这里就会产生一个传播性,使用起来很麻烦,对于这种情况,我们可以采用laterBound

    在定义Wrapper结构体的的时候不加约束,但是将inner类型作为private字段

    1. // so we can use later bound the solve this problem
    2. // we remove the where clause on struct and make inner private
    3. pub struct LaterBoundWrapper<I> {
    4. inner: I
    5. }

    提供一个工厂方法

    1. impl <I> LaterBoundWrapper<I> {
    2. // and we add constraint on new method, that means, whenever we want a Wrapper
    3. // we have to create it through our factory method, and that will make sure
    4. // only object that implement std::fmt::Debug can be used
    5. pub fn new(d: I) -> Self
    6. where I: std::fmt::Debug
    7. {
    8. LaterBoundWrapper {
    9. inner: d
    10. }
    11. }
    12. // we have to add an inspect function here
    13. pub fn inspect(&self) where I: std::fmt::Debug {
    14. println!("inspect inner {:?}", self.inner);
    15. }
    16. }

    这样当接收 LaterBoundWrapper<T> 的时候就不需要再做泛型约束了,但是由于inner变成了一个private方法,同时此时的T没有了 Debug trait的约束,就需要新增一个inspect方法,也就是要将 LaterBoundWrapper 内聚

    1. // we can remove the constraint on the take_later_bound_wrapper now
    2. pub fn take_later_bound_wrapper<T>(w: LaterBoundWrapper<T>) {
    3. // we can't debug here, as we don't know if inner is Debug
    4. // println!("{:?}", w.inner);
    5. w.inspect();
    6. }