我如何使用@字符作为 Rust 装饰器来实现结构的特征?
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
How could i use decorator with if possible @ character to have python style taste while implementing traits on my structs ?
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
trait 定义不正确,只是尝试编译它会告诉您(即使没有实现它):字段不是 traits 中的有效概念。
此外,这看起来像是某种伪 OO 层次结构,这可能不是个好主意。
在我的结构上实现特征时,我如何使用带有 @ 字符的装饰器来获得 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
How could i use decorator with if possible @ character to have python style taste while implementing traits on my structs ?
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
trait 定义不正确,只是尝试编译它会告诉您(即使没有实现它):字段不是 traits 中的有效概念。
此外,这看起来像是某种伪 OO 层次结构,这可能不是个好主意。