Can derives be auto-inserted

Say I have a project where I've to do #[derive(Debug, PartialEq)] on each and every enum or struct.
That's very quickly adding LoC to the project & reducing readability.

If I want to derive the above 2 traits for all structs or enums, is this doable somehow?
Or.. is this a valid thing to request syntax sugar for?

It's adding 1 line per type. How does it reduce readability?

You can technically make a macro that generates the struct definitions with #[derive(…)] attached. But you probably shouldn't do that. A #[derive(…)] is already a shorthand for an implementation. It's not really worth hiding it, that would reduce readability.

2 Likes

Plus you probably don't (shouldn't) want to derive always the same traits for all your types. Example : PartialEq isn't relevant for every type.

1 Like

Plus you probably don't (shouldn't) want to derive always the same traits for all your types. Example : PartialEq isn't relevant for every type.

What if I do... :slight_smile:
Just gave PartialEq as an example.

It's adding 1 line per type. How does it reduce readability?

Good point. Sorry, should have just said LoC.

This sounds like the problem solved by generic implementations.

In general, Rust uses composition over inheritance and prefer to require explicit syntax, so there may not be a language feature that is as flexible as what you are looking for.

Hmm.. it's not for deriving or implementing traits but just tagging structs or enums with specific derive statements.

#[derive(Debug, Serialize, Deserialize)]
pub struct A {
  ...
}

When there are a 100+ structs to define, that's 100+ #[derive(...)] statements.

It's also 100+ struct statements, some multiple of that per field, and any attributes on those fields, as well as comments on those fields, and the struct, and some number of impl blocks. Saving one line per struct is not a significant amount of work saved. Design a working project with 100+ structs, then compare that effort to copy/pasting a derive attribute 100+ times: it'll be nothing.

Now imagine trying to special case the N structs of those 100+ that can't support your automatic derive.

3 Likes

I'm going to argue that's easily worth the extra SLOC for the maintainability you get in return relative to some kind of meta-macro that derives derive statements.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.