macro_rules! impl_from {
(<$($generic:ident),+> in $($rest:tt)+) => { ... };
(<const $($rest:tt)+) => { ... };
(<$generic:ident, $($rest:tt)+) => { ... };
(@impl [$($generic:tt)*] $from:ty => $this:ty $(,)?) => { ... };
(@impl [$($generic:tt)*] $from:ty => $this:ty : $field:ident in $($wrapper:tt)+) => { ... };
(@impl [$($generic:tt)*] $from:ty => $this:ty : $field:ident $(,)?) => { ... };
(@impl [$($generic:tt)*] $from:ty => $($target:tt)+) => { ... };
(@tuple [$($generic:tt)*] [$from:ty] [$($this:tt)+] in $($wrapper:tt)+) => { ... };
(@tuple [$($generic:tt)*] [$from:ty] [$($this:tt)*] $next:tt $($rest:tt)+) => { ... };
(@wrap [$($generic:tt)*] $from:ty => $this:ty : $field:tt in $($wrapper:tt)+) => { ... };
(@new $value:ident; $($segment:ident)::+ $(,)?) => { ... };
(@new $value:ident; ::$($segment:ident)::+ $(,)?) => { ... };
(@new $value:ident; $wrapper:ty $(,)?) => { ... };
($from:ty => $($target:tt)+) => { ... };
}Expand description
Implement From for a struct.
Declare type and const parameters before in.
ยงExamples
With a newtype struct:
use impl_more::impl_from;
struct Foo(String);
impl_from!(String => Foo);
let foo = Foo::from("bar".to_owned());With a named field struct with type parameters:
use std::rc::Rc;
use impl_more::impl_from;
struct Foo<T> { inner: Rc<T> }
impl_from!(<T> in Rc<T> => Foo<T> : inner);
let foo = Foo::from(Rc::new("bar".to_owned()));With type and const parameters:
struct Array<T, const N: usize>([T; N]);
impl_more::impl_from!(<T, const N: usize> in [T; N] => Array<T, N>);
let value = Array::from([1, 2, 3]);
assert_eq!(value.0, [1, 2, 3]);Append in Wrapper after the destination type or field name to call
Wrapper::new(input). Use a type in scope or a qualified path.
struct Message(Box<String>);
impl_more::impl_from!(String => Message in Box);
assert_eq!(*Message::from(String::from("hello")).0, "hello");
struct Batch<T, const N: usize> { items: Box<[T; N]> }
impl_more::impl_from!(<T, const N: usize> in [T; N] => Batch<T, N> : items in Box);
assert_eq!(*Batch::from([1, 2, 3]).items, [1, 2, 3]);The wrapper can also be a user-defined type:
struct Label(String);
impl Label {
fn new(input: &str) -> Self {
Self(input.to_owned())
}
}
struct Message { label: Label }
impl_more::impl_from!(&str => Message : label in Label);
assert_eq!(Message::from("hello").label.0, "hello");