trait Actor{
fn actor(&self);
}
trait Health{
fn health(&self);
}
struct Plant;
impl Actor for Plant{
fn actor(&self){
println!("Plant Actor");
}
}
struct Monster{
health: f32
}
impl Actor for Monster{
fn actor(&self){
println!("Monster Actor");
}
}
impl Health for Monster{
fn health(&self){
println!("Health: {}",self.health);
}
}
fn main() {
let plant = Box::new(Plant);
let monster = Box::new(Monster{health: 100f32});
let mut actors : Vec<Box<Actor>> = Vec::new();
actors.push(plant);
actors.push(monster);
for a in &actors{
a.actor();
/* Would this be possible?
let health = a.get_trait_object::<Health>();
match health{
Some(h) => {h.health();},
None => {println!("Has no Health trait");}
}
*/
}
}
我想知道这样的事情是否可行?
let health = a.get_trait_object::<Health>();
match health{
Some(h) => {h.health();},
None => {println!("Has no Health trait");}
}
答案 0 :(得分:6)
从1.0开始,没有。 Rust没有提供任何动态向下转型支持,Any
除外;但是,这只允许您向下转换为值的特定具体类型,而不是指向具体类型实现的任意特征。
我相信你可以手动实现这样的投射,但这需要不安全的代码,这很容易出错;不是那种我想在SO答案中尝试和总结的东西。
答案 1 :(得分:5)
目前在Rust中不可能这样做,也不可能成为可能;但是,可以构建类似的抽象作为你的特征的一部分:
trait Actor {
fn health(&self) -> Option<&Health>;
}
trait Health { }
impl Actor for Monster {
fn health(&self) -> Option<&Health> { Some(self) }
}
impl Health for Monster { }
impl Actor for Plant {
fn health(&self) -> Option<&Health> { None }
}
预计Rust会在某个时刻出现负面界限;当它到来时,你将能够拥有这样的东西:
trait MaybeImplements<Trait: ?Sized> {
fn as_trait_ref(&self) -> Option<&Trait>;
}
macro_rules! impl_maybe_implements {
($trait_:ident) => {
impl<T: $trait_> MaybeImplements<$trait_> for T {
fn as_trait_ref(&self) -> Option<&$trait_> {
Some(self)
}
}
impl<T: !$trait_> MaybeImplements<$trait_> for T {
fn as_trait_ref(&self) -> Option<&$trait_> {
None
}
}
}
}
impl_maybe_implements!(Health);
trait Actor: MaybeImplements<Health> {
}
let health: Option<&Health> = actor.as_trait_ref();
这会将每个特征的每个实现的样板减少到每个特征一个,但是那个阶段还没有到我们这里。不过,你可以采取两种方法的中间立场:
trait MaybeImplements<Trait: ?Sized> {
fn as_trait_ref(&self) -> Option<&Trait>;
}
macro_rules! register_impl {
($trait_:ident for $ty:ty) => {
impl MaybeImplements<$trait_> for $ty {
fn as_trait_ref(&self) -> Option<$trait_> {
Some(self)
}
}
}
(!$trait_:ident for $ty:ty) => {
impl MaybeImplements<$trait_> for $ty {
fn as_trait_ref(&self) -> Option<$trait_> {
None
}
}
}
}
register_impl!(Health for Monster);
register_impl!(!Health for Plant);
以不同的方式处理它,直到找到你喜欢的东西!可能性是无限的! (因为Rust是Turing-complete。)