Trait nom::lib::std::prelude::v1::rust_2015::From 1.0.0[−][src]
pub trait From<T> {
fn from(T) -> Self;
}
Expand description
Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
Into
.
One should always prefer implementing From
over Into
because implementing From
automatically provides one with an implementation of Into
thanks to the blanket implementation in the standard library.
Only implement Into
when targeting a version prior to Rust 1.41 and converting to a type
outside the current crate.
From
was not able to do these types of conversions in earlier versions because of Rust’s
orphaning rules.
See Into
for more details.
Prefer using Into
over using From
when specifying trait bounds on a generic function.
This way, types that directly implement Into
can be used as arguments as well.
The From
is also very useful when performing error handling. When constructing a function
that is capable of failing, the return type will generally be of the form Result<T, E>
.
The From
trait simplifies error handling by allowing a function to return a single error type
that encapsulate multiple error types. See the “Examples” section and the book for more
details.
Note: This trait must not fail. If the conversion can fail, use TryFrom
.
Generic Implementations
From<T> for U
impliesInto
<U> for T
From
is reflexive, which means thatFrom<T> for T
is implemented
Examples
String
implements From<&str>
:
An explicit conversion from a &str
to a String is done as follows:
let string = "hello".to_string();
let other_string = String::from("hello");
assert_eq!(string, other_string);
While performing error handling it is often useful to implement From
for your own error type.
By converting underlying error types to our own custom error type that encapsulates the
underlying error type, we can return a single error type without losing information on the
underlying cause. The ‘?’ operator automatically converts the underlying error type to our
custom error type by calling Into<CliError>::into
which is automatically provided when
implementing From
. The compiler then infers which implementation of Into
should be used.
use std::fs;
use std::io;
use std::num;
enum CliError {
IoError(io::Error),
ParseError(num::ParseIntError),
}
impl From<io::Error> for CliError {
fn from(error: io::Error) -> Self {
CliError::IoError(error)
}
}
impl From<num::ParseIntError> for CliError {
fn from(error: num::ParseIntError) -> Self {
CliError::ParseError(error)
}
}
fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
let mut contents = fs::read_to_string(&file_name)?;
let num: i32 = contents.trim().parse()?;
Ok(num)
}
Required methods
Implementations on Foreign Types
Creates an IpAddr::V6
from an eight element 16-bit array.
Examples
use std::net::{IpAddr, Ipv6Addr};
let addr = IpAddr::from([
525u16, 524u16, 523u16, 522u16,
521u16, 520u16, 519u16, 518u16,
]);
assert_eq!(
IpAddr::V6(Ipv6Addr::new(
0x20d, 0x20c,
0x20b, 0x20a,
0x209, 0x208,
0x207, 0x206
)),
addr
);
Converts a RecvError
into a RecvTimeoutError
.
This conversion always returns RecvTimeoutError::Disconnected
.
No data is allocated on the heap.
Creates an Ipv6Addr
from an eight element 16-bit array.
Examples
use std::net::Ipv6Addr;
let addr = Ipv6Addr::from([
525u16, 524u16, 523u16, 522u16,
521u16, 520u16, 519u16, 518u16,
]);
assert_eq!(
Ipv6Addr::new(
0x20d, 0x20c,
0x20b, 0x20a,
0x209, 0x208,
0x207, 0x206
),
addr
);
Converts a RecvError
into a TryRecvError
.
This conversion always returns TryRecvError::Disconnected
.
No data is allocated on the heap.
Converts a SocketAddrV6
into a SocketAddr::V6
.
Creates a new instance of an RwLock<T>
which is unlocked.
This is equivalent to RwLock::new
.
Converts a ChildStdout
into a Stdio
Examples
ChildStdout
will be converted to Stdio
using Stdio::from
under the hood.
use std::process::{Command, Stdio};
let hello = Command::new("echo")
.arg("Hello, world!")
.stdout(Stdio::piped())
.spawn()
.expect("failed echo command");
let reverse = Command::new("rev")
.stdin(hello.stdout.unwrap()) // Converted into a Stdio here
.output()
.expect("failed reverse command");
assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
Create a new cell with its contents set to value
.
Example
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
let a = SyncOnceCell::from(3);
let b = SyncOnceCell::new();
b.set(3)?;
assert_eq!(a, b);
Ok(())
Converts a File
into a Stdio
Examples
File
will be converted to Stdio
using Stdio::from
under the hood.
use std::fs::File;
use std::process::Command;
// With the `foo.txt` file containing `Hello, world!"
let file = File::open("foo.txt").unwrap();
let reverse = Command::new("rev")
.stdin(file) // Implicit File conversion into a Stdio
.output()
.expect("failed reverse command");
assert_eq!(reverse.stdout, b"!dlrow ,olleH");
Converts a SendError<T>
into a TrySendError<T>
.
This conversion always returns a TrySendError::Disconnected
containing the data in the SendError<T>
.
No data is allocated on the heap.
Converts a tuple struct (Into<IpAddr
>, u16
) into a SocketAddr
.
This conversion creates a SocketAddr::V4
for an IpAddr::V4
and creates a SocketAddr::V6
for an IpAddr::V6
.
u16
is treated as port of the newly created SocketAddr
.
Converts a SocketAddrV4
into a SocketAddr::V4
.
Creates a new mutex in an unlocked state ready for use.
This is equivalent to Mutex::new
.
Converts a ChildStderr
into a Stdio
Examples
use std::process::{Command, Stdio};
let reverse = Command::new("rev")
.arg("non_existing_file.txt")
.stderr(Stdio::piped())
.spawn()
.expect("failed reverse command");
let cat = Command::new("cat")
.arg("-")
.stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
.output()
.expect("failed echo command");
assert_eq!(
String::from_utf8_lossy(&cat.stdout),
"rev: cannot open non_existing_file.txt: No such file or directory\n"
);
Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly.
Creates an Ipv6Addr
from a sixteen element byte array.
Examples
use std::net::Ipv6Addr;
let addr = Ipv6Addr::from([
25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
]);
assert_eq!(
Ipv6Addr::new(
0x1918, 0x1716,
0x1514, 0x1312,
0x1110, 0x0f0e,
0x0d0c, 0x0b0a
),
addr
);
Creates an IpAddr::V6
from a sixteen element byte array.
Examples
use std::net::{IpAddr, Ipv6Addr};
let addr = IpAddr::from([
25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
]);
assert_eq!(
IpAddr::V6(Ipv6Addr::new(
0x1918, 0x1716,
0x1514, 0x1312,
0x1110, 0x0f0e,
0x0d0c, 0x0b0a
)),
addr
);
Converts a ChildStdin
into a Stdio
Examples
ChildStdin
will be converted to Stdio
using Stdio::from
under the hood.
use std::process::{Command, Stdio};
let reverse = Command::new("rev")
.stdin(Stdio::piped())
.spawn()
.expect("failed reverse command");
let _echo = Command::new("echo")
.arg("Hello, world!")
.stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
.output()
.expect("failed echo command");
// "!dlrow ,olleH" echoed to console
Converts NonZeroI16
to NonZeroIsize
losslessly.
Converts a NonZeroUsize
into an usize
Converts NonZeroI64
to NonZeroI128
losslessly.
Converts NonZeroI16
to NonZeroI64
losslessly.
Converts NonZeroU8
to NonZeroU128
losslessly.
Converts NonZeroI32
to NonZeroI64
losslessly.
Converts NonZeroU16
to NonZeroI32
losslessly.
Converts NonZeroU32
to NonZeroI128
losslessly.
Converts a NonZeroIsize
into an isize
Converts a NonZeroU16
into an u16
Converts an usize
into an AtomicUsize
.
Converts NonZeroI32
to NonZeroI128
losslessly.
Converts NonZeroU8
to NonZeroU64
losslessly.
Converts NonZeroU16
to NonZeroU64
losslessly.
Converts NonZeroU8
to NonZeroI16
losslessly.
Converts NonZeroU8
to NonZeroI64
losslessly.
Converts NonZeroU16
to NonZeroU32
losslessly.
Converts NonZeroU8
to NonZeroIsize
losslessly.
Converts NonZeroI8
to NonZeroIsize
losslessly.
Converts a NonZeroU64
into an u64
Converts NonZeroU16
to NonZeroUsize
losslessly.
Converts NonZeroU32
to NonZeroU128
losslessly.
Converts a NonZeroI64
into an i64
Converts a NonZeroU128
into an u128
Converts NonZeroU64
to NonZeroI128
losslessly.
Converts NonZeroI8
to NonZeroI64
losslessly.
Converts NonZeroU8
to NonZeroI32
losslessly.
Converts an isize
into an AtomicIsize
.
Converts a NonZeroI32
into an i32
Converts NonZeroU16
to NonZeroU128
losslessly.
Converts a NonZeroU32
into an u32
Maps a byte in 0x00..=0xFF to a char
whose code point has the same value, in U+0000..=U+00FF.
Unicode is designed such that this effectively decodes bytes with the character encoding that IANA calls ISO-8859-1. This encoding is compatible with ASCII.
Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen), which leaves some “blanks”, byte values that are not assigned to any character. ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.
Note that this is also different from Windows-1252 a.k.a. code page 1252, which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks to punctuation and various Latin characters.
To confuse things further, on the Web
ascii
, iso-8859-1
, and windows-1252
are all aliases
for a superset of Windows-1252 that fills the remaining blanks with corresponding
C0 and C1 control codes.
Converts a NonZeroI128
into an i128
Converts NonZeroI16
to NonZeroI32
losslessly.
Converts a bool
into an AtomicBool
.
Examples
use std::sync::atomic::AtomicBool;
let atomic_bool = AtomicBool::from(true);
assert_eq!(format!("{:?}", atomic_bool), "true")
Converts NonZeroU8
to NonZeroU16
losslessly.
Converts NonZeroI8
to NonZeroI16
losslessly.
Converts NonZeroI8
to NonZeroI128
losslessly.
Converts NonZeroU16
to NonZeroI128
losslessly.
Converts NonZeroU8
to NonZeroI128
losslessly.
Converts NonZeroU8
to NonZeroUsize
losslessly.
Converts NonZeroI8
to NonZeroI32
losslessly.
Converts NonZeroU32
to NonZeroI64
losslessly.
Converts NonZeroU32
to NonZeroU64
losslessly.
Converts NonZeroU8
to NonZeroU32
losslessly.
Converts NonZeroU64
to NonZeroU128
losslessly.
Converts NonZeroU16
to NonZeroI64
losslessly.
Converts a NonZeroI16
into an i16
Converts NonZeroI16
to NonZeroI128
losslessly.
Create an ArrayVec
from an array.
use arrayvec::ArrayVec;
let mut array = ArrayVec::from([1, 2, 3]);
assert_eq!(array.len(), 3);
assert_eq!(array.capacity(), 3);
Implementors
impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global> where
E: 'a + Error + Send + Sync,
impl<'a, T> From<Cow<'a, [T]>> for Vec<T, Global> where
[T]: ToOwned,
<[T] as ToOwned>::Owned == Vec<T, Global>,
impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState> where
K: Eq + Hash,
Stability note: This impl does not yet exist, but we are “reserving space” to add it in the future. See rust-lang/rust#64715 for details.