Parameter Inversion in `matches!()`

What does this code output?

#[()]
pub enum  {
    ,
    
}

fn () {
    let  = ::;

    if !(::, ) {
        !("{fruit:?} is Apple");
    } else {
        !("{fruit:?} is Orange");
    }
}

Free fruit at the fruit store if you guessed Orange is Apple!

During development, I frequently ignore common compiler warnings like unused variables because they are usually leftovers from past versions of code that I clean up later. It bit me today because I accidentally inverted the order of parameters in the matches! macro, which matched Fruit::Apple to the catch-all variable fruit (unrelated to the local variable declared on line 10).

This can be seen with cargo-expand:

#![(prelude_import)]
#[]
use ::::::*;
#[]
extern crate ;
pub enum  {
    ,
    ,
}
#[]
impl :::::: for  {
    #[]
    fn (&, : &mut ::::::) -> :::::: {
        ::::::::(
            ,
            match  {
                :: => "Apple",
                :: => "Orange",
            },
        )
    }
}
fn () {
    let  = ::;
    if match :: {
         => true,
        _ => false,
    } {
        {
            ::::::(!("{0:?} is Apple\n", ));
        };
    } else {
        {
            ::::::(!("{0:?} is Orange\n", ));
        };
    }
}

To be fair, the compiler does raise a warning, but it's vague and as previously mentioned, easily glossed over:

warning: unused variable: `fruit`
  --> src/main.rs:11:31
   |
11 |     if matches!(Fruit::Apple, fruit) {
   |                               ^^^^^ help: if this is intentional, prefix it with an underscore: `_fruit`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: `testing` (bin "testing") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/testing`
Orange is Apple
core::macros::builtin
macro derive

Attribute macro used to apply derive macros.

See the reference for more info.

core::fmt::macros
macro Debug

Derive macro generating an impl of the trait Debug.

codeintel::block_b051e6f9d20d6da9
pub enum Fruit {
    Apple,
    Orange,
}
codeintel::block_b051e6f9d20d6da9::Fruit
Apple = 0
codeintel::block_b051e6f9d20d6da9::Fruit
Orange = 1
codeintel::block_b051e6f9d20d6da9
fn main()
let fruit: Fruit
core::macros
macro_rules! matches

Returns whether the given expression matches the provided pattern.

The pattern syntax is exactly the same as found in a match arm. The optional if guard can be used to add additional checks that must be true for the matched value, otherwise this macro will return false.

When testing that a value matches a pattern, it’s generally preferable to use assert_matches as it will print the debug representation of the value if the assertion fails.

Examples

let foo = 'f';
assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));

let bar = Some(4);
assert!(matches!(bar, Some(x) if x > 2));
std::macros
macro_rules! println

Prints to the standard output, with a newline.

On all platforms, the newline is the LINE FEED character (\n/U+000A) alone (no additional CARRIAGE RETURN (\r/U+000D)).

This macro uses the same syntax as format, but writes to the standard output instead. See [std::fmt] for more information.

The println! macro will lock the standard output on each call. If you call println! within a hot loop, this behavior may be the bottleneck of the loop. To avoid this, lock stdout with io::stdout().lock():

use std::io::{stdout, Write};

let mut lock = stdout().lock();
writeln!(lock, "hello world").unwrap();

Use println! only for the primary output of your program. Use [eprintln!] instead to print error and progress messages.

See the formatting documentation in std::fmt for details of the macro argument syntax.

Panics

Panics if writing to [io::stdout] fails.

Writing to non-blocking stdout can cause an error, which will lead this macro to panic.

Examples

println!(); // prints just a newline
println!("hello there!");
println!("format {} arguments", "some");
let local_variable = "some";
println!("format {local_variable} arguments");
#[feature]

Valid forms are:

  • #[feature(name1, name2, …)]
#[prelude_import]

Valid forms are:

  • #[prelude_import]
extern crate std

The Rust Standard Library

The Rust Standard Library is the foundation of portable Rust software, a set of minimal and battle-tested shared abstractions for the broader Rust ecosystem. It offers core types, like [Vec<T>] and [Option<T>], library-defined operations on language primitives, standard macros, [I/O] and [multithreading], among many other things.

std is available to all Rust crates by default. Therefore, the standard library can be accessed in use statements through the path std, as in use std::env.

How to read this documentation

If you already know the name of what you are looking for, the fastest way to find it is to use the search button at the top of the page.

Otherwise, you may want to jump to one of these useful sections:

If this is your first time, the documentation for the standard library is written to be casually perused. Clicking on interesting things should generally lead you to interesting places. Still, there are important bits you don’t want to miss, so read on for a tour of the standard library and its documentation!

Once you are familiar with the contents of the standard library you may begin to find the verbosity of the prose distracting. At this stage in your development you may want to press the “ Summary” button near the top of the page to collapse it into a more skimmable view.

While you are looking at the top of the page, also notice the “Source” link. Rust’s API documentation comes with the source code and you are encouraged to read it. The standard library source is generally high quality and a peek behind the curtains is often enlightening.

What is in the standard library documentation?

First of all, The Rust Standard Library is divided into a number of focused modules, all listed further down this page. These modules are the bedrock upon which all of Rust is forged, and they have mighty names like [std::slice] and [std::cmp]. Modules’ documentation typically includes an overview of the module along with examples, and are a smart place to start familiarizing yourself with the library.

Second, implicit methods on primitive types are documented here. This can be a source of confusion for two reasons:

  1. While primitives are implemented by the compiler, the standard libraryimplements methods directly on the primitive types (and it is the onlylibrary that does so), which are documented in the section on primitives.
  2. The standard library exports many modules with the same name as primitive types. These define additional items related to the primitivetype, but not the all-important methods.

So for example there is a page for the primitive type char that lists all the methods that can be called on characters (very useful), and there is a page for the module std::char that documents iterator and error types created by these methods (rarely useful).

Note the documentation for the primitives [str] and [T] (also called ‘slice’). Many method calls on String and [Vec<T>] are actually calls to methods on [str] and [T] respectively, via deref coercions.

Third, the standard library defines [The Rust Prelude], a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive, making the prelude documentation a good entry point to learning about the library.

And finally, the standard library exports a number of standard macros, and lists them on this page (technically, not all of the standard macros are defined by the standard library - some are defined by the compiler - but they are documented here the same). Like the prelude, the standard macros are imported by default into all crates.

Contributing changes to the documentation

Check out the Rust contribution guidelines here. The source for this documentation can be found on GitHub in the ‘library/std/’ directory. To contribute changes, make sure you read the guidelines first, then submit pull-requests for your suggested changes.

Contributions are appreciated! If you see a part of the docs that can be improved, submit a PR, or chat with us first on Zulip #docs.

A Tour of The Rust Standard Library

The rest of this crate documentation is dedicated to pointing out notable features of The Rust Standard Library.

Containers and collections

The option and result modules define optional and error-handling types, [Option<T>] and [Result<T, E>]. The iter module defines Rust’s iterator trait, Iterator, which works with the for loop to access collections.

The standard library exposes three common ways to deal with contiguous regions of memory:

  • [Vec<T>] - A heap-allocated vector that is resizable at runtime.
  • [T; N] - An inline array with a fixed size at compile time.
  • [T] - A dynamically sized slice into any other kind of contiguousstorage, whether heap-allocated or not.

Slices can only be handled through some kind of pointer, and as such come in many flavors such as:

  • &[T] - shared slice
  • &mut [T] - mutable slice
  • Box<[T]> - owned slice

[str], a UTF-8 string slice, is a primitive type, and the standard library defines many methods for it. Rust [str]s are typically accessed as immutable references: &str. Use the owned String for building and mutating strings.

For converting to strings use the format macro, and for converting from strings use the [FromStr] trait.

Data may be shared by placing it in a reference-counted box or the [Rc] type, and if further contained in a [Cell] or [RefCell], may be mutated as well as shared. Likewise, in a concurrent setting it is common to pair an atomically-reference-counted box, [Arc], with a [Mutex] to get the same effect.

The collections module defines maps, sets, linked lists and other typical collection types, including the common [HashMap<K, V>].

Platform abstractions and I/O

Besides basic data types, the standard library is largely concerned with abstracting over differences in common platforms, most notably Windows and Unix derivatives.

Common types of I/O, including [files], [TCP], and [UDP], are defined in the io, fs, and net modules.

The thread module contains Rust’s threading abstractions. sync contains further primitive shared memory types, including [atomic], [mpmc] and [mpsc], which contains the channel types for message passing.

Use before and after main()

Many parts of the standard library are expected to work before and after main(); but this is not guaranteed or ensured by tests. It is recommended that you write your own tests and run them on each platform you wish to support. This means that use of std before/after main, especially of features that interact with the OS or global state, is exempted from stability and portability guarantees and instead only provided on a best-effort basis. Nevertheless bug reports are appreciated.

On the other hand core and alloc are most likely to work in such environments with the caveat that any hookable behavior such as panics, oom handling or allocators will also depend on the compatibility of the hooks.

Some features may also behave differently outside main, e.g. stdio could become unbuffered, some panics might turn into aborts, backtraces might not get symbolicated or similar.

Non-exhaustive list of known limitations:

  • after-main use of thread-locals, which also affects additional features:
  • under UNIX, before main, file descriptors 0, 1, and 2 may be unchanged(they are guaranteed to be open during main,and are opened to /dev/null O_RDWR if they weren’t open on program start)
std
pub mod prelude

The Rust Prelude

Rust comes with a variety of things in its standard library. However, if you had to manually import every single thing that you used, it would be very verbose. But importing a lot of things that a program never uses isn’t good either. A balance needs to be struck.

The prelude is the list of things that Rust automatically imports into every Rust program. It’s kept as small as possible, and is focused on things, particularly traits, which are used in almost every single Rust program.

Other preludes

Preludes can be seen as a pattern to make using multiple types more convenient. As such, you’ll find other preludes in the standard library, such as [std::io::prelude]. Various libraries in the Rust ecosystem may also define their own preludes.

The difference between ‘the prelude’ and these other preludes is that they are not automatically use’d, and must be imported manually. This is still easier than importing all of their constituent components.

Prelude contents

The items included in the prelude depend on the edition of the crate. The first version of the prelude is used in Rust 2015 and Rust 2018, and lives in [std::prelude::v1]. [std::prelude::rust_2015] and [std::prelude::rust_2018] re-export this prelude. It re-exports the following:

[std::marker]::{Copy, Send, Sized, Sync, Unpin}, marker traits that indicate fundamental properties of types.

[std::ops]::{Fn, FnMut, FnOnce}, and their analogous async traits, [std::ops]::{AsyncFn, AsyncFnMut, AsyncFnOnce}.

[std::ops]::Drop, for implementing destructors.

[std::mem]::drop, a convenience function for explicitly dropping a value.

[std::mem]::{size_of, size_of_val}, to get the size of a type or value.

[std::mem]::{align_of, align_of_val}, to get the alignment of a type or value.

[std::boxed]::Box, a way to allocate values on the heap.

[std::borrow]::ToOwned, the conversion trait that defines [to_owned], the generic method for creating an owned type from a borrowed type.

[std::clone]::Clone, the ubiquitous trait that defines clone, the method for producing a copy of a value.

[std::cmp]::{PartialEq, PartialOrd, Eq, Ord}, the comparison traits, which implement the comparison operators and are often seen in trait bounds.

[std::convert]::{AsRef, AsMut, Into, From}, generic conversions, used by savvy API authors to create overloaded methods.

[std::default]::Default, types that have default values.

std::iter::{Iterator, Extend, IntoIterator, DoubleEndedIterator, ExactSizeIterator}, iterators of various kinds.

[std::option]::Option::{self, Some, None}, a type which expresses the presence or absence of a value. This type is so commonly used, its variants are also exported.

[std::result]::Result::{self, Ok, Err}, a type for functions that may succeed or fail. Like Option, its variants are exported as well.

[std::string]::{String, ToString}, heap-allocated strings.

[std::vec]::Vec, a growable, heap-allocated vector.

The prelude used in Rust 2021, [std::prelude::rust_2021], includes all of the above, and in addition re-exports:

[std::convert]::{TryFrom, TryInto}.

The prelude used in Rust 2024, [std::prelude::rust_2024], includes all of the above, and in addition re-exports:

[std::future]::{[Future], [IntoFuture]}.

std::prelude
pub mod rust_2021

The 2021 version of the prelude of The Rust Standard Library.

See the module-level documentation for more.

#[macro_use]

Valid forms are:

  • #[macro_use]
  • #[macro_use(name1, name2, …)]
codeintel::block_9fce4ee1be84aa2d
extern crate std

The Rust Standard Library

The Rust Standard Library is the foundation of portable Rust software, a set of minimal and battle-tested shared abstractions for the broader Rust ecosystem. It offers core types, like [Vec<T>] and [Option<T>], library-defined operations on language primitives, standard macros, [I/O] and [multithreading], among many other things.

std is available to all Rust crates by default. Therefore, the standard library can be accessed in use statements through the path std, as in use std::env.

How to read this documentation

If you already know the name of what you are looking for, the fastest way to find it is to use the search button at the top of the page.

Otherwise, you may want to jump to one of these useful sections:

If this is your first time, the documentation for the standard library is written to be casually perused. Clicking on interesting things should generally lead you to interesting places. Still, there are important bits you don’t want to miss, so read on for a tour of the standard library and its documentation!

Once you are familiar with the contents of the standard library you may begin to find the verbosity of the prose distracting. At this stage in your development you may want to press the “ Summary” button near the top of the page to collapse it into a more skimmable view.

While you are looking at the top of the page, also notice the “Source” link. Rust’s API documentation comes with the source code and you are encouraged to read it. The standard library source is generally high quality and a peek behind the curtains is often enlightening.

What is in the standard library documentation?

First of all, The Rust Standard Library is divided into a number of focused modules, all listed further down this page. These modules are the bedrock upon which all of Rust is forged, and they have mighty names like [std::slice] and [std::cmp]. Modules’ documentation typically includes an overview of the module along with examples, and are a smart place to start familiarizing yourself with the library.

Second, implicit methods on primitive types are documented here. This can be a source of confusion for two reasons:

  1. While primitives are implemented by the compiler, the standard libraryimplements methods directly on the primitive types (and it is the onlylibrary that does so), which are documented in the section on primitives.
  2. The standard library exports many modules with the same name as primitive types. These define additional items related to the primitivetype, but not the all-important methods.

So for example there is a page for the primitive type char that lists all the methods that can be called on characters (very useful), and there is a page for the module std::char that documents iterator and error types created by these methods (rarely useful).

Note the documentation for the primitives [str] and [T] (also called ‘slice’). Many method calls on String and [Vec<T>] are actually calls to methods on [str] and [T] respectively, via deref coercions.

Third, the standard library defines [The Rust Prelude], a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive, making the prelude documentation a good entry point to learning about the library.

And finally, the standard library exports a number of standard macros, and lists them on this page (technically, not all of the standard macros are defined by the standard library - some are defined by the compiler - but they are documented here the same). Like the prelude, the standard macros are imported by default into all crates.

Contributing changes to the documentation

Check out the Rust contribution guidelines here. The source for this documentation can be found on GitHub in the ‘library/std/’ directory. To contribute changes, make sure you read the guidelines first, then submit pull-requests for your suggested changes.

Contributions are appreciated! If you see a part of the docs that can be improved, submit a PR, or chat with us first on Zulip #docs.

A Tour of The Rust Standard Library

The rest of this crate documentation is dedicated to pointing out notable features of The Rust Standard Library.

Containers and collections

The option and result modules define optional and error-handling types, [Option<T>] and [Result<T, E>]. The iter module defines Rust’s iterator trait, Iterator, which works with the for loop to access collections.

The standard library exposes three common ways to deal with contiguous regions of memory:

  • [Vec<T>] - A heap-allocated vector that is resizable at runtime.
  • [T; N] - An inline array with a fixed size at compile time.
  • [T] - A dynamically sized slice into any other kind of contiguousstorage, whether heap-allocated or not.

Slices can only be handled through some kind of pointer, and as such come in many flavors such as:

  • &[T] - shared slice
  • &mut [T] - mutable slice
  • Box<[T]> - owned slice

[str], a UTF-8 string slice, is a primitive type, and the standard library defines many methods for it. Rust [str]s are typically accessed as immutable references: &str. Use the owned String for building and mutating strings.

For converting to strings use the format macro, and for converting from strings use the [FromStr] trait.

Data may be shared by placing it in a reference-counted box or the [Rc] type, and if further contained in a [Cell] or [RefCell], may be mutated as well as shared. Likewise, in a concurrent setting it is common to pair an atomically-reference-counted box, [Arc], with a [Mutex] to get the same effect.

The collections module defines maps, sets, linked lists and other typical collection types, including the common [HashMap<K, V>].

Platform abstractions and I/O

Besides basic data types, the standard library is largely concerned with abstracting over differences in common platforms, most notably Windows and Unix derivatives.

Common types of I/O, including [files], [TCP], and [UDP], are defined in the io, fs, and net modules.

The thread module contains Rust’s threading abstractions. sync contains further primitive shared memory types, including [atomic], [mpmc] and [mpsc], which contains the channel types for message passing.

Use before and after main()

Many parts of the standard library are expected to work before and after main(); but this is not guaranteed or ensured by tests. It is recommended that you write your own tests and run them on each platform you wish to support. This means that use of std before/after main, especially of features that interact with the OS or global state, is exempted from stability and portability guarantees and instead only provided on a best-effort basis. Nevertheless bug reports are appreciated.

On the other hand core and alloc are most likely to work in such environments with the caveat that any hookable behavior such as panics, oom handling or allocators will also depend on the compatibility of the hooks.

Some features may also behave differently outside main, e.g. stdio could become unbuffered, some panics might turn into aborts, backtraces might not get symbolicated or similar.

Non-exhaustive list of known limitations:

  • after-main use of thread-locals, which also affects additional features:
  • under UNIX, before main, file descriptors 0, 1, and 2 may be unchanged(they are guaranteed to be open during main,and are opened to /dev/null O_RDWR if they weren’t open on program start)
codeintel::block_9fce4ee1be84aa2d
pub enum Fruit {
    Apple,
    Orange,
}
codeintel::block_9fce4ee1be84aa2d::Fruit
Apple = 0
codeintel::block_9fce4ee1be84aa2d::Fruit
Orange = 1
#[automatically_derived]

Valid forms are:

  • #[automatically_derived]
extern crate core

The Rust Core Library

The Rust Core Library is the dependency-freefree foundation of The Rust Standard Library. It is the portable glue between the language and its libraries, defining the intrinsic and primitive building blocks of all Rust code. It links to no upstream libraries, no system libraries, and no libc.

  • Strictly speaking, there are some symbols which are needed but they aren’t always necessary.

  • The core library is minimal: it isn’t even aware of heap allocation, nor does it provide concurrency or I/O. These things require platform integration, and this library is platform-agnostic.

    How to use the core library

    Please note that all of these details are currently not considered stable.

    This library is built on the assumption of a few existing symbols:

    • memcpy, memmove, memset, memcmp, bcmp, strlen - These are core memory routines which are generated by Rust codegen backends. Additionally, this library can make explicit calls to strlen. Their signatures are the same as found in C, but there are extra assumptions about their semantics: For memcpy, memmove, memset, memcmp, and bcmp, if the n parameter is 0, the function is assumed to not be UB, even if the pointers are NULL or dangling. (Note that making extra assumptions about these functions is common among compilers: clang and GCC do the same.) These functions are often provided by the system libc, but can also be provided by the compiler-builtins crate. Note that the library does not guarantee that it will always make these assumptions, so Rust user code directly calling the C functions should follow the C specification! The advice for Rust user code is to call the functions provided by this library instead (such as ptr::copy).

    • Panic handler - This function takes one argument, a &panic::PanicInfo. It is up to consumers of this core library to define this panic function; it is only required to never return. You should mark your implementation using #[panic_handler].

    • rust_eh_personality - is used by the failure mechanisms of the compiler. This is often mapped to GCC’s personality function, but crates which do not trigger a panic can be assured that this function is never called. The lang attribute is called eh_personality.

    core
    pub mod fmt

    Utilities for formatting and printing strings.

    core::fmt
    pub trait Debug
    where
        Self: PointeeSized,

    ? formatting.

    Debug should format the output in a programmer-facing, debugging context.

    Generally speaking, you should just derive a Debug implementation.

    When used with the alternate format specifier #?, the output is pretty-printed.

    For more information on formatters, see the module-level documentation.

    This trait can be used with #[derive] if all fields implement Debug. When derived for structs, it will use the name of the struct, then {, then a comma-separated list of each field’s name and Debug value, then }. For enums, it will use the name of the variant and, if applicable, (, then the Debug values of the fields, then ).

    Stability

    Derived Debug formats are not stable, and so may change with future Rust versions. Additionally, Debug implementations of types provided by the standard library (std, core, alloc, etc.) are not stable, and may also change with future Rust versions.

    Examples

    Deriving an implementation:

    #[derive(Debug)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let origin = Point { x: 0, y: 0 };
    
    assert_eq!(
        format!("The origin is: {origin:?}"),
        "The origin is: Point { x: 0, y: 0 }",
    );

    Manually implementing:

    use std::fmt;
    
    struct Point {
        x: i32,
        y: i32,
    }
    
    impl fmt::Debug for Point {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("Point")
             .field("x", &self.x)
             .field("y", &self.y)
             .finish()
        }
    }
    
    let origin = Point { x: 0, y: 0 };
    
    assert_eq!(
        format!("The origin is: {origin:?}"),
        "The origin is: Point { x: 0, y: 0 }",
    );

    There are a number of helper methods on the Formatter struct to help you with manual implementations, such as [debug_struct].

    Types that do not wish to use the standard suite of debug representations provided by the Formatter trait (debug_struct, debug_tuple, debug_list, debug_set, debug_map) can do something totally custom by manually writing an arbitrary representation to the Formatter.

    impl fmt::Debug for Point {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "Point [{} {}]", self.x, self.y)
        }
    }

    Debug implementations using either derive or the debug builder API on Formatter support pretty-printing using the alternate flag: {:#?}.

    Pretty-printing with #?:

    #[derive(Debug)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let origin = Point { x: 0, y: 0 };
    
    let expected = "The origin is: Point {
        x: 0,
        y: 0,
    }";
    assert_eq!(format!("The origin is: {origin:#?}"), expected);
    #[inline]

    Valid forms are:

    • #[inline]
    • #[inline(always|never)]
    codeintel::block_9fce4ee1be84aa2d::Fruit
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result

    Examples

    use std::fmt;
    
    struct Position {
        longitude: f32,
        latitude: f32,
    }
    
    impl fmt::Debug for Position {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_tuple("")
             .field(&self.longitude)
             .field(&self.latitude)
             .finish()
        }
    }
    
    let position = Position { longitude: 1.987, latitude: 2.983 };
    assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
    
    assert_eq!(format!("{position:#?}"), "(
        1.987,
        2.983,
    )");
    self: &Fruit
    f: &mut Formatter<'_>
    core::fmt
    pub struct Formatter<'a> {
        options: FormattingOptions,
        buf: &'a mut (dyn Write + 'a),
    }

    Configuration for formatting.

    A Formatter represents various options related to formatting. Users do not construct Formatters directly; a mutable reference to one is passed to the fmt method of all formatting traits, like Debug and Display.

    To interact with a Formatter, you’ll call various methods to change the various options related to formatting. For examples, please see the documentation of the methods defined on Formatter below.

    core::fmt
    pub type Result = result::Result<(), Error>

    The type returned by formatter methods.

    Examples

    use std::fmt;
    
    #[derive(Debug)]
    struct Triangle {
        a: f32,
        b: f32,
        c: f32
    }
    
    impl fmt::Display for Triangle {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "({}, {}, {})", self.a, self.b, self.c)
        }
    }
    
    let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
    
    assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
    core::fmt::Formatter
    impl<'a> Formatter<'a>
    pub fn write_str(&mut self, data: &str) -> Result

    Writes some data to the underlying buffer contained within this formatter.

    Examples

    use std::fmt;
    
    struct Foo;
    
    impl fmt::Display for Foo {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("Foo")
            // This is equivalent to:
            // write!(formatter, "Foo")
        }
    }
    
    assert_eq!(format!("{Foo}"), "Foo");
    assert_eq!(format!("{Foo:0>8}"), "Foo");
    codeintel::block_9fce4ee1be84aa2d
    fn main()
    std
    pub mod io

    Traits, helpers, and type definitions for core I/O functionality.

    The std::io module contains a number of common things you’ll need when doing input and output. The most core part of this module is the Read and Write traits, which provide the most general interface for reading and writing input and output.

    Read and Write

    Because they are traits, Read and Write are implemented by a number of other types, and you can implement them for your types too. As such, you’ll see a few different types of I/O throughout the documentation in this module: [File]s, [TcpStream]s, and sometimes even Vec<T>s. For example, Read adds a read method, which we can use on [File]s:

    use std::io;
    use std::io::prelude::*;
    use std::fs::File;
    
    fn main() -> io::Result<()> {
        let mut f = File::open("foo.txt")?;
        let mut buffer = [0; 10];
    
        // read up to 10 bytes
        let n = f.read(&mut buffer)?;
    
        println!("The bytes: {:?}", &buffer[..n]);
        Ok(())
    }

    Read and Write are so important, implementors of the two traits have a nickname: readers and writers. So you’ll sometimes see ‘a reader’ instead of ‘a type that implements the Read trait’. Much easier!

    Seek and BufRead

    Beyond that, there are two important traits that are provided: Seek and BufRead. Both of these build on top of a reader to control how the reading happens. Seek lets you control where the next byte is coming from:

    use std::io;
    use std::io::prelude::*;
    use std::io::SeekFrom;
    use std::fs::File;
    
    fn main() -> io::Result<()> {
        let mut f = File::open("foo.txt")?;
        let mut buffer = [0; 10];
    
        // skip to the last 10 bytes of the file
        f.seek(SeekFrom::End(-10))?;
    
        // read up to 10 bytes
        let n = f.read(&mut buffer)?;
    
        println!("The bytes: {:?}", &buffer[..n]);
        Ok(())
    }

    BufRead uses an internal buffer to provide a number of other ways to read, but to show it off, we’ll need to talk about buffers in general. Keep reading!

    BufReader and BufWriter

    Byte-based interfaces are unwieldy and can be inefficient, as we’d need to be making near-constant calls to the operating system. To help with this, std::io comes with two structs, BufReader and BufWriter, which wrap readers and writers. The wrapper uses a buffer, reducing the number of calls and providing nicer methods for accessing exactly what you want.

    For example, BufReader works with the BufRead trait to add extra methods to any reader:

    use std::io;
    use std::io::prelude::*;
    use std::io::BufReader;
    use std::fs::File;
    
    fn main() -> io::Result<()> {
        let f = File::open("foo.txt")?;
        let mut reader = BufReader::new(f);
        let mut buffer = String::new();
    
        // read a line into buffer
        reader.read_line(&mut buffer)?;
    
        println!("{buffer}");
        Ok(())
    }

    BufWriter doesn’t add any new ways of writing; it just buffers every call to write:

    use std::io;
    use std::io::prelude::*;
    use std::io::BufWriter;
    use std::fs::File;
    
    fn main() -> io::Result<()> {
        let f = File::create("foo.txt")?;
        {
            let mut writer = BufWriter::new(f);
    
            // write a byte to the buffer
            writer.write(&[42])?;
    
        } // the buffer is flushed once writer goes out of scope
    
        Ok(())
    }

    Standard input and output

    A very common source of input is standard input:

    use std::io;
    
    fn main() -> io::Result<()> {
        let mut input = String::new();
    
        io::stdin().read_line(&mut input)?;
    
        println!("You typed: {}", input.trim());
        Ok(())
    }

    Note that you cannot use the ? operator in functions that do not return a Result<T, E>. Instead, you can call [.unwrap()] or match on the return value to catch any possible errors:

    use std::io;
    
    let mut input = String::new();
    
    io::stdin().read_line(&mut input).unwrap();

    And a very common source of output is standard output:

    use std::io;
    use std::io::prelude::*;
    
    fn main() -> io::Result<()> {
        io::stdout().write(&[42])?;
        Ok(())
    }

    Of course, using [io::stdout] directly is less common than something like println.

    Iterator types

    A large number of the structures provided by std::io are for various ways of iterating over I/O. For example, Lines is used to split over lines:

    use std::io;
    use std::io::prelude::*;
    use std::io::BufReader;
    use std::fs::File;
    
    fn main() -> io::Result<()> {
        let f = File::open("foo.txt")?;
        let reader = BufReader::new(f);
    
        for line in reader.lines() {
            println!("{}", line?);
        }
        Ok(())
    }

    Functions

    There are a number of functions that offer access to various features. For example, we can use three of these functions to copy everything from standard input to standard output:

    use std::io;
    
    fn main() -> io::Result<()> {
        io::copy(&mut io::stdin(), &mut io::stdout())?;
        Ok(())
    }

    io::Result

    Last, but certainly not least, is [io::Result]. This type is used as the return type of many std::io functions that can cause an error, and can be returned from your own functions as well. Many of the examples in this module use the ? operator:

    use std::io;
    
    fn read_input() -> io::Result<()> {
        let mut input = String::new();
    
        io::stdin().read_line(&mut input)?;
    
        println!("You typed: {}", input.trim());
    
        Ok(())
    }

    The return type of read_input(), io::Result<()>, is a very common type for functions which don’t have a ‘real’ return value, but do want to return errors if they happen. In this case, the only purpose of this function is to read the line and print it, so we use ().

    Platform-specific behavior

    Many I/O functions throughout the standard library are documented to indicate what various library or syscalls they are delegated to. This is done to help applications both understand what’s happening under the hood as well as investigate any possibly unclear semantics. Note, however, that this is informative, not a binding contract. The implementation of many of these functions are subject to change over time and may call fewer or more syscalls/library functions.

    I/O Safety

    Rust follows an I/O safety discipline that is comparable to its memory safety discipline. This means that file descriptors can be exclusively owned. (Here, “file descriptor” is meant to subsume similar concepts that exist across a wide range of operating systems even if they might use a different name, such as “handle”.) An exclusively owned file descriptor is one that no other code is allowed to access in any way, but the owner is allowed to access and even close it any time. A type that owns its file descriptor should usually close it in its drop function. Types like [File] own their file descriptor. Similarly, file descriptors can be borrowed, granting the temporary right to perform operations on this file descriptor. This indicates that the file descriptor will not be closed for the lifetime of the borrow, but it does not imply any right to close this file descriptor, since it will likely be owned by someone else.

    The platform-specific parts of the Rust standard library expose types that reflect these concepts, see os::unix and os::windows.

    To uphold I/O safety, it is crucial that no code acts on file descriptors it does not own or borrow, and no code closes file descriptors it does not own. In other words, a safe function that takes a regular integer, treats it as a file descriptor, and acts on it, is unsound.

    Not upholding I/O safety and acting on a file descriptor without proof of ownership can lead to misbehavior and even Undefined Behavior in code that relies on ownership of its file descriptors: a closed file descriptor could be re-allocated, so the original owner of that file descriptor is now working on the wrong file. Some code might even rely on fully encapsulating its file descriptors with no operations being performed by any other part of the program.

    Note that exclusive ownership of a file descriptor does not imply exclusive ownership of the underlying kernel object that the file descriptor references (also called “open file description” on some operating systems). File descriptors basically work like [Arc]: when you receive an owned file descriptor, you cannot know whether there are any other file descriptors that reference the same kernel object. However, when you create a new kernel object, you know that you are holding the only reference to it. Just be careful not to lend it to anyone, since they can obtain a clone and then you can no longer know what the reference count is! In that sense, OwnedFd is like Arc and BorrowedFd<'a> is like &'a Arc (and similar for the Windows types). In particular, given a BorrowedFd<'a>, you are not allowed to close the file descriptor – just like how, given a &'a Arc, you are not allowed to decrement the reference count and potentially free the underlying object. There is no equivalent to Box for file descriptors in the standard library (that would be a type that guarantees that the reference count is 1), however, it would be possible for a crate to define a type with those semantics.

    std::io::stdio
    pub fn _print(args: fmt::Arguments<'_>)
    core::macros::builtin
    macro_rules! format_args

    Constructs parameters for the other string-formatting macros.

    This macro functions by taking a formatting string literal containing {} for each additional argument passed. format_args! prepares the additional parameters to ensure the output can be interpreted as a string and canonicalizes the arguments into a single type. Any value that implements the [Display] trait can be passed to format_args!, as can any [Debug] implementation be passed to a {:?} within the formatting string.

    This macro produces a value of type [fmt::Arguments]. This value can be passed to the macros within std::fmt for performing useful redirection. All other formatting macros (format!, write, println!, etc) are proxied through this one. format_args!, unlike its derived macros, avoids heap allocations.

    You can use the [fmt::Arguments] value that format_args! returns in Debug and Display contexts as seen below. The example also shows that Debug and Display format to the same thing: the interpolated format string in format_args!.

    let args = format_args!("{} foo {:?}", 1, 2);
    let debug = format!("{args:?}");
    let display = format!("{args}");
    assert_eq!("1 foo 2", display);
    assert_eq!(display, debug);

    See the formatting documentation in std::fmt for details of the macro argument syntax, and further information.

    Examples

    use std::fmt;
    
    let s = fmt::format(format_args!("hello {}", "world"));
    assert_eq!(s, format!("hello {}", "world"));

    Argument lifetimes

    Except when no formatting arguments are used, the produced fmt::Arguments value borrows temporary values. To allow it to be stored for later use, the arguments’ lifetimes, as well as those of temporaries they borrow, may be extended when format_args! appears in the initializer expression of a let statement. The syntactic rules used to determine when temporaries’ lifetimes are extended are documented in the Reference.