IndexMut需要Index时如何为自定义Trait实现trait IndexMut,Index是为自定义trait的supertrait实现的
How to implement trait IndexMut for custom Trait when IndexMut requires Index, which is implemented for the supertrait of the custom trait
假设我有这个代码
trait Indexable {
fn get(&self, index: usize) -> &bool;
}
trait IndexableMut: Indexable {
fn get_mut(&mut self, index: usize) -> &mut bool;
}
impl Index<usize> for dyn Indexable {
type Output = bool;
fn index(&self, index: usize) -> &Self::Output {
self.get(index)
}
}
是否可以实施
impl IndexMut<usize> for dyn IndexableMut {
fn index(&mut self, index: usize) -> &mut Self::Output {
self.get_mut(index)
}
}
没有为 IndexableMut
显式实施 Index<usize>
没有。 Index<usize>
是IndexMut<usize>
的supertrait,所以如果要实现IndexMut
就必须实现Index
。
Indexable
是 IndexableMut
的超特征这一事实无关紧要,因为 dyn Indexable
和 dyn IndexableMut
仍然是不同的类型。仅仅因为 dyn Indexable
实现了 Index<usize>
并不意味着 dyn IndexableMut
实现了。
假设我有这个代码
trait Indexable {
fn get(&self, index: usize) -> &bool;
}
trait IndexableMut: Indexable {
fn get_mut(&mut self, index: usize) -> &mut bool;
}
impl Index<usize> for dyn Indexable {
type Output = bool;
fn index(&self, index: usize) -> &Self::Output {
self.get(index)
}
}
是否可以实施
impl IndexMut<usize> for dyn IndexableMut {
fn index(&mut self, index: usize) -> &mut Self::Output {
self.get_mut(index)
}
}
没有为 IndexableMut
Index<usize>
没有。 Index<usize>
是IndexMut<usize>
的supertrait,所以如果要实现IndexMut
就必须实现Index
。
Indexable
是 IndexableMut
的超特征这一事实无关紧要,因为 dyn Indexable
和 dyn IndexableMut
仍然是不同的类型。仅仅因为 dyn Indexable
实现了 Index<usize>
并不意味着 dyn IndexableMut
实现了。