【问题标题】:how could i use @ character as a Rust decorator to implement trait to a struct?我如何使用 @ 字符作为 Rust 装饰器来实现结构的特征?
【发布时间】:2020-05-07 04:47:45
【问题描述】:

如果可能的话,我如何使用带有 @ 字符的装饰器在我的结构上实现特征时具有 python 风格的味道?

trait Animal {
    fn get_name(&self) -> &str {
        &self.name
    }
}

trait Felidae {
    fn to_claw(&self) -> &str;{
        println!("i can scratch off !");
    }
}


struct Dog {
    name: String,
}

struct Cat {
    name: String,
}

@Animal
Dog

@Animal,Felidae
Cat

【问题讨论】:

标签: python struct rust decorator traits


【解决方案1】:

如果可能的话,我如何使用带有 @ 字符的装饰器在我的结构上实现特征时具有 python 风格的味道?

Rust 不是 Python,Rust 不使用 @ 字符或运行时装饰。但是,正如 zgerd 指出的那样,您可以定义 custom derives ,这样您就可以编写类似

#[derive(Animal)]
struct Dog {...}

我强烈质疑它在这种情况下的价值,因为实施并不繁琐:

trait Animal {
    fn get_name(&self) -> &str;
}
trait Felidae {
    fn to_claw(&self) {
        println!("i can scratch off !");
    }
}

struct Dog {
    name: String,
}
impl Animal for Dog {
    fn get_name(&self) -> &str { &self.name }
}

struct Cat {
    name: String,
}
impl Animal for Cat {
    fn get_name(&self) -> &str { &self.name }
}
impl Felidae for Cat {}

最多,对于这样一个简单的特征,你可以写一个基本的declarative macro:

macro_rules! animal_impl {
    ($t: ty) => {
        impl Animal for $t {
            fn get_name(&self) -> &str { &self.name }
        }
    }
}
animal_impl!{Dog}
animal_impl!{Cat}

That's what most of the standard library does to reduce boilerplate,尽管我什至不会打扰,除非您需要在大约六种类型上实现这种自相似的实现。

另请注意,您的 Animal 特征定义不正确,仅尝试编译它就会告诉您(即使没有实现它):字段不是特征中的有效概念。

而且这看起来像是某种伪 OO 层次结构,这可能是个坏主意。

【讨论】:

  • 我正在尝试采用 Rust 的思维方式,并且我开始学习实体组件系统...感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多