Rust:条件特质继承

3
例如,我想为 Rust 中的容器编写特性(trait):
trait Container: Default {
    type ValueType;
}

但我也希望所有的Container都可以在Container::ValueType可被Clone时进行Clone:

// 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 特质的意图,而不是为实现类型。

1个回答

7

有类似的语法:

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

但这并不是一个条件性的实现,Container 只能用于满足所有约束的类型:包括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();
}

如果你要实现具体类型的 Clone,无论如何都必须这样做。

如果你的目标仅仅是表明当容器元素是 Clone 时,容器应该被克隆,那么 Rust 中常规的模式是在需要时只约束必要的部分(即如果一个函数需要克隆容器,则约束为 C: Clone;如果函数只需要克隆元素,则约束为 C::ValueType: Clone)。


我以前从未见过 where Self::ValueType: Clone 的语法。这是否意味着与使用 type ValueType: CloneValueType 上指定约束的含义相同? - user4815162342
2
@user4815162342 在这种情况下,它们是相同的,我更喜欢后者。where语法可用,因为它可以应用于更多的事物。例如:trait Container: Iterator where Self::Item: Clone - kmdreko
1
哦,好的,那很有道理,我在那个变体中也看到过。在更复杂的特质中,它通常被澄清为 where <Self as Iterator>::Item: Clone - user4815162342

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接