简体   繁体   中英

how could i use @ character as a Rust decorator to implement trait to a struct?

How could i use decorator with if possible @ character to have python style taste while implementing traits on my structs?

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 is not Python, Rust doesn't use the @ character or runtime decoration. As zgerd points out you can, however, define custom derives which would let you write something like

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

I highly question the value of it in this case as the implementations are not exactly onerous:

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 {}

At most , for such a simple trait you'd write a basic 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 , though I wouldn't even bother unless you need such self-similar implementation on a good half-dozen types or so.

Also note that your Animal trait definition is not correct, which simply trying to compile it would have told you (even without implementing it): fields are not a valid concept in traits.

Also this looks like some sort of pseudo-OO hierarchy thing, which is likely a bad idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM