Trait sgx_tstd::convert::From1.0.0[][src]

pub trait From<T> {
    fn from(T) -> Self;
}

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>.

Generic Implementations

Examples

String implements From<&str>:

let string = "hello".to_string();
let other_string = String::from("hello");

assert_eq!(string, other_string);

An example usage for error handling:

use std::io::{self, Read};
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 file = std::fs::File::open("test")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    let num: i32 = contents.trim().parse()?;
    Ok(num)
}

Required Methods

Performs the conversion.

Implementations on Foreign Types

impl From<LocalWaker> for Waker
[src]

impl<T> From<T> for Poll<T>
[src]

impl<'a, T> From<FutureObj<'a, T>> for LocalFutureObj<'a, T>
[src]

impl<'a, F> From<Box<F>> for LocalFutureObj<'a, ()> where
    F: 'a + Future<Output = ()>, 
[src]

impl<T> From<Arc<T>> for Waker where
    T: Wake + 'static, 
[src]

impl<'a, F> From<PinBox<F>> for FutureObj<'a, ()> where
    F: 'a + Send + Future<Output = ()>, 
[src]

impl<'a, F> From<Box<F>> for FutureObj<'a, ()> where
    F: 'a + Send + Future<Output = ()>, 
[src]

impl<'a, F> From<PinBox<F>> for LocalFutureObj<'a, ()> where
    F: 'a + Future<Output = ()>, 
[src]

Implementors