derive-new icon indicating copy to clipboard operation
derive-new copied to clipboard

implement `into` and `into_iter`

Open OmarTawfik opened this issue 2 years ago • 3 comments

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.md and lib.rs.

Please let me know if I can do anything else.

OmarTawfik avatar Dec 15 '23 12:12 OmarTawfik

cc @nrc

Closes #43 Closes #62

OmarTawfik avatar Dec 15 '23 12:12 OmarTawfik

@nrc Is it possible to merge this PR please? This would be a time-saver for a lot of projects

DenisGorbachev avatar Apr 26 '24 05:04 DenisGorbachev

@nrc friendly ping

polarathene avatar May 28 '24 14:05 polarathene