implement `into` and `into_iter`
Thank you for the awesome crate! Here is a feature suggestion, that is sorely missed in our projects. It has also been requested twice already (#43 and #62).
#[new(into)]
To make type conversion easier, #[new(into)] attribute changes the parameter type to impl Into<T>, and populates the field with value.into(). This is useful for containers like strings, accepting a String or a &str:
#[derive(new)]
struct Foo {
#[new(into)]
x: String,
}
let _ = Foo::new("Hello".to_string());
let _ = Foo::new(format!("Hello"));
let _ = Foo::new("Hello");
It is also useful for wrapping types like Box<T> and Rc<T>, without having to wrap at every callsite:
#[derive(new)]
struct Foo {
#[new(into)]
x: Rc<Bar>,
}
let _ = Foo::new(Rc::new(bar));
let _ = Foo::new(bar.into());
let _ = Foo::new(bar);
#[new(into_iter = "T")]
For iterators/collections, #[new(into_iter = "T")] attribute changes the parameter type to impl IntoIterator<Item = T>, and populates the field with value.into_iter().collect(). This allows initializing with a variety of types, like [T], Option<T>, Vec<T>, sets, maps, and even other iterators:
#[derive(new)]
struct Foo {
#[new(into_iter = "bool")]
x: Vec<bool>,
}
let _ = Foo::new(vec![true, false]);
let _ = Foo::new([true, false]);
let _ = Foo::new(Some(true));
About this PR
I split this into three parts to make reviewing easier:
- https://github.com/nrc/derive-new/commit/08e5390e70001360691cabc82fec7d0523fada24 fixes broken integration tests (I suspect CI is out of date).
- https://github.com/nrc/derive-new/commit/3e310d9751e8db31519184e7623678adb6a76f5f fixes formatting for a couple of files (using the default
cargo fmt). - https://github.com/nrc/derive-new/commit/8f608804e3cb8752a0690003f93d822d3041a9ba implements the feature, adding tests, and documentation to both
README.mdandlib.rs.
Please let me know if I can do anything else.
cc @nrc
Closes #43 Closes #62
@nrc Is it possible to merge this PR please? This would be a time-saver for a lot of projects
@nrc friendly ping