Macro From
macro_rules! From { ... }
What #[derive(From)] generates
The point of deriving this type is that it makes it easy to create a new
instance of the type by using the .into() method on the value(s) that it
should contain. This is done by implementing the From trait for the type
that is passed to the derive.
Structs
For structs with a single field you can call .into() on the desired content
itself after deriving From.
# use From;
#
;
assert_eq!;
For structs that have multiple fields .into() needs to be called on a tuple
containing the desired content for each field.
# use From;
#
;
assert_eq!;
To specify concrete types to derive convert from use #[from(<types>)].
# use Cow;
#
# use From;
#
;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Also, you can forward implementation to the inner type, which means deriving From for any type, that derives From
inner type.
# use Cow;
#
# use From;
#
assert_eq!;
assert_eq!;
assert_eq!;
Enums
For enums .into() works for each variant as if they were structs. This
includes specifying concrete types via #[from(<types>)] or forwarding
implementation with #[from(forward)].
# use From;
#
assert_eq!;
assert_eq!;
By default, From is generated for every enum variant, but you can skip some
variants via #[from(skip)] (or #[from(ignore)]) or only concrete fields via #[from].
#
// Is equivalent to:
#
Example usage
# use From;
#
// Allow converting from i32
;
// Forward from call to the field, so allow converting
// from anything that can be converted into an i64 (so most integers)
;
// You can ignore a variant
// Or explicitly annotate the ones you need
// And even specify additional conversions for them
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;