Open mmstick opened 6 years ago
Seconded. In one of my projects, I find myself wrapping things in a Box
and cloning &str
s to String
s a lot. It’d be nice if there was a way to specify this in a derive attribute. Something like:
#[derive(new)]
pub struct Foo {
#[new(eval = "Box::new(bar)")] bar: Box<Bar>,
baz: Baz,
}
The exact keyword is up for debate: eval
, expr
, apply
, convert
etc.
Also, if this is even possible: instead of repeating the field name, a shorthand could be introduced to represent the input parameter for the field, e.g. it
or <>
or _
.
A common use-case for me along these lines is making the argument impl Into<T>
and the field T
. This feature would enable that use-case, but I wonder if a dedicated attribute for this use-case would make sense:
#[derive(new)]
pub struct Person {
#[new(into)]
name: String;
}
Another common use-case for me that this feature would help with, but which might also justify dedicated syntax is to clone the input expression.
#[derive(new)]
pub struct Shared {
#[new(cloned)]
write: Arc<Something>,
}
The addition of into
and into_iter
in #43 has been helpful for singular fields.
Not sure about custom expressions, but also a dedicated owned
could support Person::new("John", ["Mary", "Beth"])
for the following?
#[derive(new)]
pub struct Person {
name: String,
#[new(into_iter="&str", owned)]
friends: Vec<String>,
}
A specific use case where this optimization would help a lot is constructing resources in kube-rs
when there are Vec<String>
fields.
There's some structures I'd like to use this with, but they require tiny adjustments to input arguments when storing them in the structure, such as subtracting 1 from an integer.