rust - Implement one trait for multiple structs at once -


i have trait footrait has bunch of functions. have structs foostruct , barstruct , want implement footrait both structs methods doing same.

is there way implement footrait both foostruct , barstruct @ once? imagined following:

impl footrait foostruct + barstruct {     // implement methods here } 

no, there no way implement 1 trait multiple structs @ same time without metaprogramming macros.

i'd go far there's no reason to, either. if had "the methods doing same", should extract common member variables different struct , implement trait struct (if need trait anymore). can add new struct member of originals.

if had like

struct dog {     hunger: u8,     wagging: bool, }  struct cat {     hunger: u8,     meowing: bool, }  trait hungry {     fn is_hungry(&self) -> bool; } 

you have

struct dog {     hunger: hunger,     wagging: bool, }  struct cat {     hunger: hunger,     meowing: bool, }  struct hunger {     level: u8, }  impl hunger {     fn is_hungry(&self) -> bool {         self.level > 100     } } 

if needed trait other reasons, can delegate it:

trait hungry {     fn is_hungry(&self) -> bool; }  impl hungry hunger {     fn is_hungry(&self) -> bool {         self.level > 100     } }  impl hungry dog {     fn is_hungry(&self) -> bool { self.hunger.is_hungry() } }  impl hungry cat {     fn is_hungry(&self) -> bool { self.hunger.is_hungry() } } 

these last 2 implementations still same, it's minimal amount of duplication. then, still hold out hope form of delegation introduced @ syntax level.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -