How do I pass fields to 'new()' using the crate 'derive_new' but not storing them?

No, you can't avoid a different field for that. The moment you use the field attribute #[new(default)] or #[new(value = "..")] the given field is removed from the arguments of the generated new associated function. You hack yourself around that limitation by adding an unused field to the struct, solely to have the value available as argument in your new function. At this point I believe it would be easier to write your new function yourself, even for a struct with a lot of fields. I used to use derive_new, but it has its limitations. If you need more complex initialization, I'd recommend taking a look at the builder pattern.

1 Like

Thanks. I'm not sure the builder pattern is appropriate for my specific case. Being able to do this with 'derive_new' would be ideal, like you can with Python dataclass' InitVar.

Hmm, maybe you could make a feature request for this? I could envision something like this to work:

use derive_new::new;

#[new(init_var("init_data", "String"))]
struct Test {
    #[new(value = "std::rc::Rc::new(init_data)")]
    data: std::rc::Rc<String>,

But again, I think it would be easier to just create the new function yourself, instead of littering your code with attributes. Another drawback of derive_new is that it doesn't add a #[allow(clippy::too_many_arguments)] to the generated function which is a nuisance for structs with a lot of fields.

Yeah something like that. Or like InitVar: #[new(init)].

Just by imagining I can see #[new(init)] or your proposal would be easier than create the new function. My actual class is much bigger, this is just an example. For now I just store, since it's just a boolean.

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.