【发布时间】:2016-10-05 21:49:39
【问题描述】:
试图覆盖 trait cast 问题,描述为 here。坚持实现特征函数,该函数返回具有自己实现的枚举实例:
//the "trait matcher" enum
enum Side<'a> {
Good(&'a GoodDude),
Bad(&'a BadDude),
}
//very general trait
trait Dude {
fn who_am_i(&self) -> Side;
fn do_useful_stuff(&self);
}
//specific trait #1
trait GoodDude: Dude {
fn who_am_i_inner(&self) -> Side {
Side::Good(&self)
}
fn save_the_world(&self);
}
//specific trait #2
trait BadDude: Dude {
fn who_am_i_inner(&self) -> Side {
Side::Bad(&self)
}
fn do_evil(&self);
}
但是由于某种原因,这部分的编译失败了E0277:
trait GoodDude: Dude {
fn who_am_i_inner(&self) -> Side {
Side::Good(&self) //&self should be &GoodDude, but compiler says it is not...
}
fn save_the_world(&self);
}
结果:
<anon>:16:20: 16:25 error: the trait `GoodDude` is not implemented for the type `&Self` [E0277]
<anon>:16 Side::Good(&self)
^~~~~
<anon>:16:20: 16:25 help: see the detailed explanation for E0277
<anon>:16:20: 16:25 note: required for the cast to the object type `GoodDude`
这可以解决吗?
完整示例:https://play.rust-lang.org/?gist=8ae2384e401da76c16214c4a642ce8b4&version=stable&backtrace=0
【问题讨论】:
-
尝试
Side::Good(self)而不是Side::Good(&self)。 -
我不能。特征的实现者可能是一个巨大的结构,我必须在那里使用借用和特征对象。此外,它会立即询问 Size(特征
core::marker::Sized未实现) -
fn name(&self)可以脱糖为fn name(self:&Self)。self变量的类型是&Self。