Rust:有条件的 trait 继承

Mic*_*uza 3 traits rust

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

trait Container: Default {
    type ValueType;
}
Run Code Online (Sandbox Code Playgroud)

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

// not Rust code
trait Container: Default + Clone if Self::ValueType: Clone {
    type ValueType;
}
Run Code Online (Sandbox Code Playgroud)

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

struct MyVec<T> {}

impl<T: Clone> Clone for MyVec<T> {/**/}
Run Code Online (Sandbox Code Playgroud)

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

kmd*_*eko 6

存在这种类似的语法:

trait Container: Default + Clone where Self::ValueType: Clone {
                              // ^^^^^
    type ValueType;
}
Run Code Online (Sandbox Code Playgroud)

但它是不是有条件的,Container只能为statisfy类型实现的所有约束:DefaultClone,和Self::ValueTypeClone


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

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

Clone无论如何,您都必须在具体类型上实现。

如果您的目标只是表明“对于Container元素是否存在的实现,则Clone容器应该被克隆”,惯用的 Rust 中的流行模式是仅在需要时才限制需要的内容。(即,如果一个函数需要克隆容器,则约束 on C: Clone;如果一个函数只需要克隆一个元素,则约束 on C::ValueType: Clone)。

  • @user4815162342 在这种情况下,它们是相同的,我更喜欢后者。“where”语法可用,因为它可以应用于更多事物。例如:`trait Container: Iterator where Self::Item: Clone`。 (2认同)