[英]how could i use @ character as a Rust decorator to implement trait to a struct?
如果可能的话,我如何使用带有 @ 字符的装饰器来获得 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 风格的味道,同时在我的结构上实现特征?
Rust 不是 Python,Rust 不使用@
字符或运行时装饰。 然而,正如 zgerd 指出的那样,您可以定义自定义派生,它可以让您编写类似的东西
#[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 {}
最多,对于这样一个简单的特征,你会编写一个基本的声明性宏:
macro_rules! animal_impl {
($t: ty) => {
impl Animal for $t {
fn get_name(&self) -> &str { &self.name }
}
}
}
animal_impl!{Dog}
animal_impl!{Cat}
这就是大多数标准库为减少样板文件所做的事情,尽管我什至不会打扰,除非您需要在六种左右的良好类型上实现这种自相似的实现。
另请注意,您的Animal
特征定义不正确,只需尝试编译它就会告诉您(即使没有实现它):字段不是特征中的有效概念。
此外,这看起来像是某种伪 OO 层次结构的东西,这可能是个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.