Yes, it looks like auto-derived impls for enums is what you are looking for.
If you want to keep something akin to your syntax, which is to swap the order of the match with the enum (in a way, your match is at the item statement), then a (probably procedural) macro could do it for you.
That is, something transforming:
match_impl! {
enum S {
Animal(String, String, usize),
Alien(String, usize),
// anything with "default" must have the same number AND type of discriminants
#[match_impl(default)]
Apples(usize),
}
impl Clone for match Self {
Self::Animal => {
fn clone (self: &'_ Self) -> Self {
// here, self.0, self.1, and self.2 exist for access
println!("Clone on animal called");
Self(self.0.clone(), self.1.clone(), self.2)
}
},
Self::Alien => {
fn clone (self: &'_ Self) -> Self {
// here, self.0 and self.1 exist for access
println!("Clone on alien called");
Self(self.0.clone(), self.1)
}
},
default => {
fn clone (self: &'_ Self) -> Self {
// here, self.0 exists for access b/c of the default keyword
println!("Clone on non-animal and non-alien type called");
Self(self.0)
}
},
}
}
into:
#[derive(Clone)]
enum S {
Animal(Animal),
Alien(Alien),
Apples(Apples),
}
struct Animal(String, String, usize);
struct Alien(String, usize);
struct Apples(usize);
impl Clone for Animal {
fn clone (self: &'_ Self) -> Self {
// here, self.0, self.1, and self.2 exist for access
println!("Clone on animal called");
Animal(self.0.clone(), self.1.clone(), self.2)
}
}
impl Clone for Alien {
fn clone (self: &'_ Self) -> Self {
// here, self.0 and self.1 exist for access
println!("Clone on alien called");
Self(self.0.clone(), self.1)
}
}
impl Clone for Apples {
fn clone (self: &'_ Self) -> Self {
// here, self.0 exists for access b/c of the default keyword
println!("Clone on non-animal and non-alien type called");
Self(self.0)
}
}
That being said, when we compare the two syntaxes, the one for the macro is not that much short than the expanded one, and it does leads to a new "custom" syntax for the language; so I am personally not convinced it is that good of an idea
, but maybe for your actual use case it could make sense?