Simple and safe type conversions in to Self. It is the reciprocal of
Into.
This trait is useful when performing error handling as described by
the book and is closely related to the ? operator.
When constructing a function that is capable of failing the return type
will generally be of the form Result<T, E>.
The From trait allows for simplification of error handling by providing a
means of returning a single error type that encapsulates numerous possible
erroneous situations.
This trait is not limited to error handling, rather the general case for
this trait would be in any type conversions to have an explicit definition
of how they are performed.
Note: this trait must not fail. If the conversion can fail, use
TryFrom or a dedicated method which returns an Option<T> or a
Result<T, E>.
From<T> for U implies Into<U>for T
from is reflexive, which means that From<T> for T is implemented
String implements From<&str>:
let string = "hello".to_string();
let other_string = String::from("hello");
assert_eq!(string, other_string);Run
An example usage for error handling:
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)
}Run
Intended for use for errors not exposed to the user, where allocating onto
the heap (for normal construction via Error::new) is too costly.
Converts an ErrorKind into an Error.
This conversion allocates a new error with a simple representation of error kind.
use std::io::{Error, ErrorKind};
let not_found = ErrorKind::NotFound;
let error = Error::from(not_found);
assert_eq!("entity not found", format!("{}", error));Run
Create an IpAddr::V6 from an eight element 16-bit array.
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
);Run
Create an IpAddr::V4 from a four element byte array.
use std::net::{IpAddr, Ipv4Addr};
let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);Run
Create an IpAddr::V6 from a sixteen element byte array.
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
);Run
use std::net::Ipv4Addr;
let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);Run
Converts a bool to a i128. The resulting value is 0 for false and 1 for true
values.
assert_eq!(i128::from(true), 1);
assert_eq!(i128::from(false), 0);Run
Converts a bool to a i16. The resulting value is 0 for false and 1 for true
values.
assert_eq!(i16::from(true), 1);
assert_eq!(i16::from(false), 0);Run
Converts a bool to a i32. The resulting value is 0 for false and 1 for true
values.
assert_eq!(i32::from(true), 1);
assert_eq!(i32::from(false), 0);Run
Converts a bool to a i64. The resulting value is 0 for false and 1 for true
values.
assert_eq!(i64::from(true), 1);
assert_eq!(i64::from(false), 0);Run
Converts a bool to a i8. The resulting value is 0 for false and 1 for true
values.
assert_eq!(i8::from(true), 1);
assert_eq!(i8::from(false), 0);Run
Converts a bool to a isize. The resulting value is 0 for false and 1 for true
values.
assert_eq!(isize::from(true), 1);
assert_eq!(isize::from(false), 0);Run
Converts a bool to a u128. The resulting value is 0 for false and 1 for true
values.
assert_eq!(u128::from(true), 1);
assert_eq!(u128::from(false), 0);Run
Converts a bool to a u16. The resulting value is 0 for false and 1 for true
values.
assert_eq!(u16::from(true), 1);
assert_eq!(u16::from(false), 0);Run
Converts a bool to a u32. The resulting value is 0 for false and 1 for true
values.
assert_eq!(u32::from(true), 1);
assert_eq!(u32::from(false), 0);Run
Converts a bool to a u64. The resulting value is 0 for false and 1 for true
values.
assert_eq!(u64::from(true), 1);
assert_eq!(u64::from(false), 0);Run
Converts a bool to a u8. The resulting value is 0 for false and 1 for true
values.
assert_eq!(u8::from(true), 1);
assert_eq!(u8::from(false), 0);Run
Converts a bool to a usize. The resulting value is 0 for false and 1 for true
values.
assert_eq!(usize::from(true), 1);
assert_eq!(usize::from(false), 0);Run
Converts a bool into an AtomicBool.
use std::sync::atomic::AtomicBool;
let atomic_bool = AtomicBool::from(true);
assert_eq!(format!("{:?}", atomic_bool), "true")Run
Converts a char into a u32.
use std::mem;
fn main() {
let c = 'c';
let u = u32::from(c);
assert!(4 == mem::size_of_val(&u))
}Run
Converts f32 to f64 losslessly.
Converts i16 to isize losslessly.
Converts i16 to f32 losslessly.
Converts i16 to f64 losslessly.
Converts i16 to i128 losslessly.
Converts i16 to i32 losslessly.
Converts i16 to i64 losslessly.
Converts an i16 into an AtomicI16.
Converts i32 to f64 losslessly.
Converts i32 to i128 losslessly.
Converts i32 to i64 losslessly.
Converts an i32 into an AtomicI32.
Converts i64 to i128 losslessly.
Converts an i64 into an AtomicI64.
Converts i8 to isize losslessly.
Converts i8 to f32 losslessly.
Converts i8 to f64 losslessly.
Converts i8 to i128 losslessly.
Converts i8 to i16 losslessly.
Converts i8 to i32 losslessly.
Converts i8 to i64 losslessly.
Converts an i8 into an AtomicI8.
Converts an isize into an AtomicIsize.
Converts u16 to usize losslessly.
Converts u16 to f32 losslessly.
Converts u16 to f64 losslessly.
Converts u16 to i128 losslessly.
Converts u16 to i32 losslessly.
Converts u16 to i64 losslessly.
Converts u16 to u128 losslessly.
Converts u16 to u32 losslessly.
Converts u16 to u64 losslessly.
Converts an u16 into an AtomicU16.
Converts u32 to f64 losslessly.
Converts u32 to i128 losslessly.
Converts u32 to i64 losslessly.
Converts u32 to u128 losslessly.
Converts u32 to u64 losslessly.
Convert a host byte order u32 into an Ipv4Addr.
use std::net::Ipv4Addr;
let addr = Ipv4Addr::from(0x0d0c0b0au32);
assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);Run
Converts an u32 into an AtomicU32.
Converts u64 to i128 losslessly.
Converts u64 to u128 losslessly.
Converts an u64 into an AtomicU64.
Maps a byte in 0x00...0xFF to a char whose code point has the same value, in U+0000 to 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 u8 into a char.
use std::mem;
fn main() {
let u = 32 as u8;
let c = char::from(u);
assert!(4 == mem::size_of_val(&c))
}Run
Converts u8 to usize losslessly.
Converts u8 to isize losslessly.
Converts u8 to f32 losslessly.
Converts u8 to f64 losslessly.
Converts u8 to i128 losslessly.
Converts u8 to i16 losslessly.
Converts u8 to i32 losslessly.
Converts u8 to i64 losslessly.
Converts u8 to u128 losslessly.
Converts u8 to u16 losslessly.
Converts u8 to u32 losslessly.
Converts u8 to u64 losslessly.
Converts an u8 into an AtomicU8.
Converts an usize into an AtomicUsize.
Converts a Box<str>> into a Box<[u8]>
This conversion does not allocate on the heap and happens in place.
let boxed: Box<str> = Box::from("hello");
let boxed_str: Box<[u8]> = Box::from(boxed);
let slice: &[u8] = &[104, 101, 108, 108, 111];
let boxed_slice = Box::from(slice);
assert_eq!(boxed_slice, boxed_str);Run
Converts the given boxed str slice to a String.
It is notable that the str slice is owned.
Basic usage:
let s1: String = String::from("hello world");
let s2: Box<str> = s1.into_boxed_str();
let s3: String = String::from(s2);
assert_eq!("hello world", s3)Run
Converts a Box<CStr> into a CString without copying or allocating.
Converts a Box<OsStr> into a OsString without copying or allocating.
Converts a Box<Path> into a PathBuf
This conversion does not allocate or copy memory.
Converts a CString into a Box<CStr> without copying or allocating.
Converts a CString into a Rc<CStr> without copying or allocating.
Converts a CString into a Arc<CStr> without copying or allocating.
Converts a CString into a Vec<u8>.
The conversion consumes the CString, and removes the terminating NUL byte.
Converts a OsString into a Box<OsStr> without copying or allocating.
Converts a OsString into a PathBuf
This conversion does not allocate or copy memory.
Converts a OsString into a Rc<OsStr> without copying or allocating.
Converts a OsString into a Arc<OsStr> without copying or allocating.
Converts a File into a Stdio
File will be converted to Stdio using Stdio::from under the hood.
use std::fs::File;
use std::process::Command;
let file = File::open("foo.txt").unwrap();
let reverse = Command::new("rev")
.stdin(file)
.output()
.expect("failed reverse command");
assert_eq!(reverse.stdout, b"!dlrow ,olleH");Run
Convert an Ipv4Addr into a host byte order u32.
use std::net::Ipv4Addr;
let addr = Ipv4Addr::new(13, 12, 11, 10);
assert_eq!(0x0d0c0b0au32, u32::from(addr));Run
Converts a PathBuf into a Box<Path>
This conversion currently should not allocate memory,
but this behavior is not guaranteed on all platforms or in all future versions.
Converts a PathBuf into a OsString
This conversion does not allocate or copy memory.
Converts a Path into a Rc by copying the Path data into a new Rc buffer.
Converts a Path into a Rc by copying the Path data into a new Rc buffer.
Converts a ChildStderr into a Stdio
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())
.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"
);Run
Converts a ChildStdin into a Stdio
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())
.output()
.expect("failed echo command");
Run
Converts a ChildStdout into a Stdio
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())
.output()
.expect("failed reverse command");
assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");Run
Converts the given String to a boxed str slice that is owned.
Basic usage:
let s1: String = String::from("hello world");
let s2: Box<str> = Box::from(s1);
let s3: String = String::from(s2);
assert_eq!("hello world", s3)Run
Converts a String into a box of dyn Error + Send + Sync.
use std::error::Error;
use std::mem;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))Run
Converts a String into a box of dyn Error.
use std::error::Error;
use std::mem;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<Error>::from(a_string_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))Run
Converts a String into a OsString.
The conversion copies the data, and includes an allocation on the heap.
Converts a String into a PathBuf
This conversion does not allocate or copy memory.
Converts the given String to a vector Vec that holds values of type u8.
Basic usage:
let s1 = String::from("hello world");
let v1 = Vec::from(s1);
for b in v1 {
println!("{}", b);
}Run
Converts a LocalWaker into a Waker.
This conversion turns a !Sync LocalWaker into a Sync Waker, allowing a wakeup
object to be sent to another thread, but giving up its ability to do specialized
thread-local wakeup behavior.
Converts a &str into a Box<str>
This conversion allocates on the heap
and performs a copy of s.
let boxed: Box<str> = Box::from("hello");
println!("{}", boxed);Run
Converts a str into a box of dyn Error.
use std::error::Error;
use std::mem;
let a_str_error = "a str error";
let a_boxed_error = Box::<Error>::from(a_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))Run
Converts a Path into a Rc by copying the Path data into a new Rc buffer.
Converts a Path into a Rc by copying the Path data into a new Rc buffer.
Converts a Cow into a box of dyn Error.
use std::error::Error;
use std::mem;
use std::borrow::Cow;
let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<Error>::from(a_cow_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))Run
Converts a str into a box of dyn Error + Send + Sync.
use std::error::Error;
use std::mem;
let a_str_error = "a str error";
let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))Run
Converts a Cow into a box of dyn Error + Send + Sync.
use std::error::Error;
use std::mem;
use std::borrow::Cow;
let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))Run
Converts a type of Error into a box of dyn Error.
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f , "An error")
}
}
impl Error for AnError {
fn description(&self) -> &str {
"Description of an error"
}
}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<Error>::from(an_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))Run
Converts a type of Error + Send + Sync into a box of dyn Error +
Send + Sync.
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f , "An error")
}
}
impl Error for AnError {
fn description(&self) -> &str {
"Description of an error"
}
}
unsafe impl Send for AnError {}
unsafe impl Sync for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))Run
Converts a &[T] into a Box<[T]>
This conversion allocates on the heap
and performs a copy of slice.
let slice: &[u8] = &[104, 101, 108, 108, 111];
let boxed_slice: Box<[u8]> = Box::from(slice);
println!("{:?}", boxed_slice);Run
Converts a Box<T> into a Pin<Box<T>>
This conversion does not allocate on the heap and happens in place.
Converts a generic type T into a Box<T>
The conversion allocates on the heap and moves t
from the stack into it.
let x = 5;
let boxed = Box::new(5);
assert_eq!(Box::from(x), boxed);Run
Creates a new mutex in an unlocked state ready for use.
This is equivalent to Mutex::new.
Creates a new instance of an RwLock<T> which is unlocked.
This is equivalent to RwLock::new.
impl<T> From<T> for T | [src] |