std::io::Error - Rust
Description: API documentation for the Rust `Error` struct in crate `std`.
Keywords: rust, rustlang, rust-lang, Error

# 1.0.0[−][src]Struct std::io::Error

    pub struct Error { /* fields omitted */ }

The error type for I/O operations of the `Read`, `Write`, `Seek`, and associated traits.

Errors mostly originate from the underlying OS, but custom instances of `Error` can be created with crafted error messages and a particular value of `ErrorKind`.

## Methods

### `impl Error`[src]

#### `pub fn new<E>(kind: ErrorKind, error: E) -> Error where
E: Into<Box<dyn Error + Send + Sync>>,` [src]

Creates a new I/O error from a known kind of error as well as an arbitrary error payload.

This function is used to generically create I/O errors which do not originate from the OS itself. The `error` argument is an arbitrary payload which will be contained in this `Error`.

# Examples

    use std::io::{Error, ErrorKind};

    // errors can be created from strings
    let custom_error = Error::new(ErrorKind::Other, "oh no!");

    // errors can also be created from other errors
    let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);Run

#### `pub fn last_os_error() -> Error`[src]

Returns an error representing the last OS error which occurred.

This function reads the value of `errno` for the target platform (e.g. `GetLastError` on Windows) and will return a corresponding instance of `Error` for the error code.

# Examples

    use std::io::Error;

    println!("last OS error: {:?}", Error::last_os_error());Run

#### `pub fn from_raw_os_error(code: i32) -> Error`[src]

Creates a new instance of an `Error` from a particular OS error code.

# Examples

On Linux:

    use std::io;

    let error = io::Error::from_raw_os_error(22);
    assert_eq!(error.kind(), io::ErrorKind::InvalidInput);Run

On Windows:

    use std::io;

    let error = io::Error::from_raw_os_error(10022);
    assert_eq!(error.kind(), io::ErrorKind::InvalidInput);Run

#### `pub fn raw_os_error(&self) -> Option<i32>`[src]

Returns the OS error that this error represents (if any).

If this `Error` was constructed via `last_os_error` or `from_raw_os_error`, then this function will return `Some`, otherwise it will return `None`.

# Examples

    use std::io::{Error, ErrorKind};

    fn print_os_error(err: &Error) {
        if let Some(raw_os_err) = err.raw_os_error() {
            println!("raw OS error: {:?}", raw_os_err);
        } else {
            println!("Not an OS error");
        }
    }

    fn main() {
        // Will print "raw OS error: ...".
        print_os_error(&Error::last_os_error());
        // Will print "Not an OS error".
        print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
    }Run

#### `pub fn get_ref(&self) -> Option<&(dyn Error + Send + Sync + 'static)>`
1.3.0
[src]

Returns a reference to the inner error wrapped by this error (if any).

If this `Error` was constructed via `new` then this function will return `Some`, otherwise it will return `None`.

# Examples

    use std::io::{Error, ErrorKind};

    fn print_error(err: &Error) {
        if let Some(inner_err) = err.get_ref() {
            println!("Inner error: {:?}", inner_err);
        } else {
            println!("No inner error");
        }
    }

    fn main() {
        // Will print "No inner error".
        print_error(&Error::last_os_error());
        // Will print "Inner error: ...".
        print_error(&Error::new(ErrorKind::Other, "oh no!"));
    }Run

#### `pub fn get_mut(&mut self) -> Option<&mut (dyn Error + Send + Sync + 'static)>`
1.3.0
[src]

Returns a mutable reference to the inner error wrapped by this error (if any).

If this `Error` was constructed via `new` then this function will return `Some`, otherwise it will return `None`.

# Examples

    use std::io::{Error, ErrorKind};
    use std::{error, fmt};
    use std::fmt::Display;

    #[derive(Debug)]
    struct MyError {
        v: String,
    }

    impl MyError {
        fn new() -> MyError {
            MyError {
                v: "oh no!".to_string()
            }
        }

        fn change_message(&mut self, new_message: &str) {
            self.v = new_message.to_string();
        }
    }

    impl error::Error for MyError {
        fn description(&self) -> &str { &self.v }
    }

    impl Display for MyError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "MyError: {}", &self.v)
        }
    }

    fn change_error(mut err: Error) -> Error {
        if let Some(inner_err) = err.get_mut() {
            inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
        }
        err
    }

    fn print_error(err: &Error) {
        if let Some(inner_err) = err.get_ref() {
            println!("Inner error: {}", inner_err);
        } else {
            println!("No inner error");
        }
    }

    fn main() {
        // Will print "No inner error".
        print_error(&change_error(Error::last_os_error()));
        // Will print "Inner error: ...".
        print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
    }Run

#### `pub fn into_inner(self) -> Option<Box<dyn Error + Send + Sync>>`
1.3.0
[src]

Consumes the `Error`, returning its inner error (if any).

If this `Error` was constructed via `new` then this function will return `Some`, otherwise it will return `None`.

# Examples

    use std::io::{Error, ErrorKind};

    fn print_error(err: Error) {
        if let Some(inner_err) = err.into_inner() {
            println!("Inner error: {}", inner_err);
        } else {
            println!("No inner error");
        }
    }

    fn main() {
        // Will print "No inner error".
        print_error(Error::last_os_error());
        // Will print "Inner error: ...".
        print_error(Error::new(ErrorKind::Other, "oh no!"));
    }Run

#### `pub fn kind(&self) -> ErrorKind`[src]

Returns the corresponding `ErrorKind` for this error.

# Examples

    use std::io::{Error, ErrorKind};

    fn print_error(err: Error) {
        println!("{:?}", err.kind());
    }

    fn main() {
        // Will print "No inner error".
        print_error(Error::last_os_error());
        // Will print "Inner error: ...".
        print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
    }Run

## Trait Implementations

### `impl Error for Error`[src]

#### `fn description(&self) -> &str`[src]

This method is soft-deprecated. Read more

#### `fn cause(&self) -> Option<&dyn Error>`[src]

Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

The lower-level cause of this error, if any. Read more

#### `fn source(&self) -> Option<&(dyn Error + 'static)>`
1.30.0
[src]

The lower-level source of this error, if any. Read more

### `impl Debug for Error`[src]

#### `fn fmt(&self, f: &mut Formatter) -> Result`[src]

Formats the value using the given formatter. Read more

### `impl Display for Error`[src]

#### `fn fmt(&self, fmt: &mut Formatter) -> Result`[src]

Formats the value using the given formatter. Read more

### `impl From<NulError> for Error`[src]

#### `fn from(_: NulError) -> Error`[src]

Converts a `NulError` into a `io::Error`.

### `impl<W> From<IntoInnerError<W>> for Error`[src]

#### `fn from(iie: IntoInnerError<W>) -> Error`[src]

Performs the conversion.

### `impl From<ErrorKind> for Error`
1.14.0
[src]

Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly.

#### `fn from(kind: ErrorKind) -> Error`[src]

Converts an `ErrorKind` into an `Error`.

This conversion allocates a new error with a simple representation of error kind.

# Examples

    use std::io::{Error, ErrorKind};

    let not_found = ErrorKind::NotFound;
    let error = Error::from(not_found);
    assert_eq!("entity not found", format!("{}", error));Run

## Auto Trait Implementations

### `impl Send for Error`

### `impl Sync for Error`

## Blanket Implementations

### `impl<T, U> TryFrom for T where
T: From<U>,` [src]

#### `type Error = !`

🔬 This is a nightly-only experimental API. (`try_from` #33417)

The type returned in the event of a conversion error.

#### `fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>`[src]

🔬 This is a nightly-only experimental API. (`try_from` #33417)

Performs the conversion.

### `impl<T> From for T`[src]

#### `fn from(t: T) -> T`[src]

Performs the conversion.

### `impl<T, U> TryInto for T where
U: TryFrom<T>,` [src]

#### `type Error = <U as TryFrom<T>>::Error`

🔬 This is a nightly-only experimental API. (`try_from` #33417)

The type returned in the event of a conversion error.

#### `fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>`[src]

🔬 This is a nightly-only experimental API. (`try_from` #33417)

Performs the conversion.

### `impl<T, U> Into for T where
U: From<T>,` [src]

#### `fn into(self) -> U`[src]

Performs the conversion.

### `impl<T> Borrow for T where
T: ?Sized,` [src]

####
ⓘImportant traits for &'_ mut I

### Important traits for &'_ mut I

`impl<'_, I> Iterator for &'_ mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<'a, R: Read + ?Sized> Read for &'a mut Rimpl<'a, W: Write + ?Sized> Write for &'a mut W`
`fn borrow(&self) -> &T`[src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut for T where
T: ?Sized,` [src]

####
ⓘImportant traits for &'_ mut I

### Important traits for &'_ mut I

`impl<'_, I> Iterator for &'_ mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<'a, R: Read + ?Sized> Read for &'a mut Rimpl<'a, W: Write + ?Sized> Write for &'a mut W`
`fn borrow_mut(&mut self) -> &mut T`[src]

Mutably borrows from an owned value. Read more

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `fn get_type_id(&self) -> TypeId`[src]

🔬 This is a nightly-only experimental API. (`get_type_id` #27745)

this method will likely be replaced by an associated static

Gets the `TypeId` of `self`. Read more

### `impl<T> ToString for T where
T: Display + ?Sized,` [src]

#### `fn to_string(&self) -> String`[src]

Converts the given value to a `String`. Read more

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g., `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`)