Rust:条件性状继承

Rust: conditional trait inheritance

例如,我想用 Rust 为容器编写 trait:

trait Container: Default {
    type ValueType;
}

但我也希望所有 Containers 也可以是 Cloned 只有当 Container::ValueType 可以是 Cloned:

// not Rust code
trait Container: Default + Clone if Self::ValueType: Clone {
    type ValueType;
}

当然,我可以有条件地为具体容器本身实现 Clone 特性:

struct MyVec<T> {}

impl<T: Clone> Clone for MyVec<T> {/**/}

或使用derive(Clone),但我想表达我对Container特征的意图,而不是实现类型。

存在类似的语法:

trait Container: Default + Clone where Self::ValueType: Clone {
                              // ^^^^^
    type ValueType;
}

但它不是有条件的,Container只能对满足所有约束的类型实现:DefaultCloneSelf::ValueTypeClone.


我不确定这是否有用。 Rust trait 约束是显式的,这意味着除非存在约束,否则你不能使用某些东西。所以无论如何你都必须将它们包含在约束中。

fn use_container<C: Container>(c: C)
where
    C: Clone,
    C::ValueType: Clone
{
  let _ = c.clone();
  let _ = c.get_element().clone();
}

而且你必须在具体类型上实现 Clone 无论如何。

如果您的目标只是表明 “对于 Container 的实现,如果元素是 Clone 那么容器应该是克隆的”,惯用的 Rust 中的流行模式是只在需要时限制你需要的东西。 (即,如果一个函数需要克隆容器,则限制在 C: Clone;如果一个函数只需要克隆一个元素,则限制在 C::ValueType: Clone)。