# Table of Contents - [Rust Documentation](#rust-documentation) - [std - Rust](#std-rust) - [The Rust Programming Language - The Rust Programming Language](#the-rust-programming-language-the-rust-programming-language) - [Introduction - The Rust Edition Guide](#introduction-the-rust-edition-guide) - [Introduction - The Rust Style Guide](#introduction-the-rust-style-guide) - [What is rustdoc? - The rustdoc book](#what-is-rustdoc-the-rustdoc-book) - [Introduction - Clippy Documentation](#introduction-clippy-documentation) - [Introduction - The Embedded Rust Book](#introduction-the-embedded-rust-book) - [Introduction - The Rustonomicon](#introduction-the-rustonomicon) - [Introduction - The Cargo Book](#introduction-the-cargo-book) - [Introduction - The Rust Reference](#introduction-the-rust-reference) - [What is rustc? - The rustc book](#what-is-rustc-the-rustc-book) - [Introduction - Rust By Example](#introduction-rust-by-example) - [Rust Release Notes](#rust-release-notes) - [Rust error codes index - Error codes index](#rust-error-codes-index-error-codes-index) - [The Unstable Book - The Rust Unstable Book](#the-unstable-book-the-rust-unstable-book) - [Settings](#settings) - [Help](#help) - [Control Scope and Privacy with Modules - The Rust Programming Language](#control-scope-and-privacy-with-modules-the-rust-programming-language) - [std_detect - Rust](#std-detect-rust) - [Data Types - The Rust Programming Language](#data-types-the-rust-programming-language) - [alloc - Rust](#alloc-rust) - [proc_macro - Rust](#proc-macro-rust) - [std::cmp - Rust](#std-cmp-rust) - [current in std::thread - Rust](#current-in-std-thread-rust) - [format in std - Rust](#format-in-std-rust) - [std::boxed - Rust](#std-boxed-rust) - [std::char - Rust](#std-char-rust) - [test - Rust](#test-rust) - [std::env - Rust](#std-env-rust) - [std::default - Rust](#std-default-rust) - [std::result - Rust](#std-result-rust) - [std::backtrace - Rust](#std-backtrace-rust) - [std::any - Rust](#std-any-rust) - [std::ascii - Rust](#std-ascii-rust) - [std::borrow - Rust](#std-borrow-rust) - [std::i8 - Rust](#std-i8-rust) - [std::thread - Rust](#std-thread-rust) - [std::i16 - Rust](#std-i16-rust) - [std::i32 - Rust](#std-i32-rust) - [std::i64 - Rust](#std-i64-rust) - [std::i128 - Rust](#std-i128-rust) - [std::isize - Rust](#std-isize-rust) - [std::clone - Rust](#std-clone-rust) - [std::option - Rust](#std-option-rust) - [std::net - Rust](#std-net-rust) - [std::sync::mpmc - Rust](#std-sync-mpmc-rust) - [std::array - Rust](#std-array-rust) - [std::assert_matches - Rust](#std-assert-matches-rust) - [std::from - Rust](#std-from-rust) - [cfg in std - Rust](#cfg-in-std-rust) - [std::sync::mpsc - Rust](#std-sync-mpsc-rust) - [std::u8 - Rust](#std-u8-rust) - [std::u16 - Rust](#std-u16-rust) - [std::u32 - Rust](#std-u32-rust) - [std::u64 - Rust](#std-u64-rust) - [std::u128 - Rust](#std-u128-rust) - [std::usize - Rust](#std-usize-rust) - [std::autodiff - Rust](#std-autodiff-rust) - [std::bstr - Rust](#std-bstr-rust) - [std::f16 - Rust](#std-f16-rust) - [std::f128 - Rust](#std-f128-rust) - [std::pat - Rust](#std-pat-rust) - [concat in std - Rust](#concat-in-std-rust) - [compile_error in std - Rust](#compile-error-in-std-rust) - [dbg in std - Rust](#dbg-in-std-rust) - [std::convert - Rust](#std-convert-rust) - [std::hint - Rust](#std-hint-rust) - [std::unsafe_binder - Rust](#std-unsafe-binder-rust) - [column in std - Rust](#column-in-std-rust) - [debug_assert_eq in std - Rust](#debug-assert-eq-in-std-rust) - [debug_assert_ne in std - Rust](#debug-assert-ne-in-std-rust) - [std::collections - Rust](#std-collections-rust) - [std::async_iter - Rust](#std-async-iter-rust) - [assert_eq in std - Rust](#assert-eq-in-std-rust) - [assert_ne in std - Rust](#assert-ne-in-std-rust) - [assert in std - Rust](#assert-in-std-rust) - [debug_assert in std - Rust](#debug-assert-in-std-rust) - [env in std - Rust](#env-in-std-rust) - [std::hash - Rust](#std-hash-rust) - [std::os - Rust](#std-os-rust) - [std::time - Rust](#std-time-rust) - [std::random - Rust](#std-random-rust) - [file in std - Rust](#file-in-std-rust) - [std::slice - Rust](#std-slice-rust) - [std::alloc - Rust](#std-alloc-rust) - [std::string - Rust](#std-string-rust) - [eprint in std - Rust](#eprint-in-std-rust) - [eprintln in std - Rust](#eprintln-in-std-rust) - [std::future - Rust](#std-future-rust) - [std::rc - Rust](#std-rc-rust) - [std::f32 - Rust](#std-f32-rust) - [std::f64 - Rust](#std-f64-rust) - [std::vec - Rust](#std-vec-rust) - [format_args in std - Rust](#format-args-in-std-rust) - [std::sync::atomic - Rust](#std-sync-atomic-rust) - [std::error - Rust](#std-error-rust) - [std::task - Rust](#std-task-rust) - [std::panic - Rust](#std-panic-rust) - [std::primitive - Rust](#std-primitive-rust) - [std::fs - Rust](#std-fs-rust) - [std::cell - Rust](#std-cell-rust) - [std::process - Rust](#std-process-rust) - [std::range - Rust](#std-range-rust) - [std::path - Rust](#std-path-rust) - [std::sync - Rust](#std-sync-rust) - [std::arch - Rust](#std-arch-rust) - [include_str in std - Rust](#include-str-in-std-rust) - [include_bytes in std - Rust](#include-bytes-in-std-rust) - [is_x86_feature_detected in std - Rust](#is-x86-feature-detected-in-std-rust) - [std::marker - Rust](#std-marker-rust) - [matches in std - Rust](#matches-in-std-rust) - [line in std - Rust](#line-in-std-rust) - [cfg_select in std - Rust](#cfg-select-in-std-rust) - [std::mem - Rust](#std-mem-rust) - [try in std - Rust](#try-in-std-rust) - [include in std - Rust](#include-in-std-rust) - [break - Rust](#break-rust) - [become - Rust](#become-rust) - [Redirecting...](#redirecting-) - [continue - Rust](#continue-rust) - [concat_bytes in std - Rust](#concat-bytes-in-std-rust) - [SelfTy - Rust](#selfty-rust) - [impl - Rust](#impl-rust) - [crate - Rust](#crate-rust) - [if - Rust](#if-rust) - [stringify in std - Rust](#stringify-in-std-rust) - [trace_macros in std - Rust](#trace-macros-in-std-rust) - [log_syntax in std - Rust](#log-syntax-in-std-rust) - [module_path in std - Rust](#module-path-in-std-rust) - [print in std - Rust](#print-in-std-rust) - [thread_local in std - Rust](#thread-local-in-std-rust) - [std::num - Rust](#std-num-rust) - [await - Rust](#await-rust) - [dyn - Rust](#dyn-rust) - [false - Rust](#false-rust) - [extern - Rust](#extern-rust) - [in - Rust](#in-rust) - [unimplemented in std - Rust](#unimplemented-in-std-rust) - [vec in std - Rust](#vec-in-std-rust) - [unreachable in std - Rust](#unreachable-in-std-rust) - [match - Rust](#match-rust) - [const_format_args in std - Rust](#const-format-args-in-std-rust) - [write in std - Rust](#write-in-std-rust) - [else - Rust](#else-rust) - [option_env in std - Rust](#option-env-in-std-rust) - [writeln in std - Rust](#writeln-in-std-rust) - [todo in std - Rust](#todo-in-std-rust) - [as - Rust](#as-rust) - [Redirecting...](#redirecting-) - [const - Rust](#const-rust) - [ref - Rust](#ref-rust) - [self - Rust](#self-rust) - [super - Rust](#super-rust) - [type - Rust](#type-rust) - [where - Rust](#where-rust) - [mut - Rust](#mut-rust) - [println in std - Rust](#println-in-std-rust) - [return - Rust](#return-rust) - [union - Rust](#union-rust) - [while - Rust](#while-rust) - [Foreword - The Rust Programming Language](#foreword-the-rust-programming-language) - [pub - Rust](#pub-rust) - [let - Rust](#let-rust) - [Installation - The Rust Programming Language](#installation-the-rust-programming-language) - [Introduction - The Rust Programming Language](#introduction-the-rust-programming-language) - [true - Rust](#true-rust) - [mod - Rust](#mod-rust) - [move - Rust](#move-rust) - [use - Rust](#use-rust) - [The Rust Programming Language - The Rust Programming Language](#the-rust-programming-language-the-rust-programming-language) - [Common Programming Concepts - The Rust Programming Language](#common-programming-concepts-the-rust-programming-language) - [Hello, World! - The Rust Programming Language](#hello-world-the-rust-programming-language) - [Hello, Cargo! - The Rust Programming Language](#hello-cargo-the-rust-programming-language) - [Closures - The Rust Programming Language](#closures-the-rust-programming-language) - [Variables and Mutability - The Rust Programming Language](#variables-and-mutability-the-rust-programming-language) - [std::str - Rust](#std-str-rust) - [Type aliases - The Rust Reference](#type-aliases-the-rust-reference) - [static - Rust](#static-rust) - [unsafe - Rust](#unsafe-rust) - [enum - Rust](#enum-rust) - [fn - Rust](#fn-rust) - [async - Rust](#async-rust) - [struct - Rust](#struct-rust) - [std::pin - Rust](#std-pin-rust) - [for - Rust](#for-rust) - [loop - Rust](#loop-rust) - [Getting Started - The Rust Programming Language](#getting-started-the-rust-programming-language) - [panic in std - Rust](#panic-in-std-rust) - [std::ffi - Rust](#std-ffi-rust) - [Programming a Guessing Game - The Rust Programming Language](#programming-a-guessing-game-the-rust-programming-language) - [trait - Rust](#trait-rust) - [Modules - The Rust Reference](#modules-the-rust-reference) - [Unions - The Rust Reference](#unions-the-rust-reference) - [std::fmt - Rust](#std-fmt-rust) - [std::ptr - Rust](#std-ptr-rust) - [Future in std::future - Rust](#future-in-std-future-rust) - [LocalKey in std::thread - Rust](#localkey-in-std-thread-rust) - [std::ops - Rust](#std-ops-rust) - [without_provenance in std::ptr - Rust](#without-provenance-in-std-ptr-rust) - [with_exposed_provenance in std::ptr - Rust](#with-exposed-provenance-in-std-ptr-rust) - [Using Structs to Structure Related Data - The Rust Programming Language](#using-structs-to-structure-related-data-the-rust-programming-language) - [Hash in std::hash - Rust](#hash-in-std-hash-rust) - [Tuple types - The Rust Reference](#tuple-types-the-rust-reference) - [Textual types - The Rust Reference](#textual-types-the-rust-reference) - [An Example Program Using Structs - The Rust Programming Language](#an-example-program-using-structs-the-rust-programming-language) - [Allocator in std::alloc - Rust](#allocator-in-std-alloc-rust) - [Redirection](#redirection) - [Receiver in std::ops - Rust](#receiver-in-std-ops-rust) - [Redirection](#redirection) - [Redirection](#redirection) - [Redirection](#redirection) - [Redirection](#redirection) - [Redirection](#redirection) - [Redirection](#redirection) - [ToString in std::string - Rust](#tostring-in-std-string-rust) - [Into in std::convert - Rust](#into-in-std-convert-rust) - [Any in std::any - Rust](#any-in-std-any-rust) - [DerefPure in std::ops - Rust](#derefpure-in-std-ops-rust) - [CloneToUninit in std::clone - Rust](#clonetouninit-in-std-clone-rust) - [Alignment in std::fmt - Rust](#alignment-in-std-fmt-rust) - [Sign in std::fmt - Rust](#sign-in-std-fmt-rust) - [DebugAsHex in std::fmt - Rust](#debugashex-in-std-fmt-rust) - [TypeId in std::any - Rust](#typeid-in-std-any-rust) - [TryReserveErrorKind in std::collections - Rust](#tryreserveerrorkind-in-std-collections-rust) - [BacktraceStyle in std::panic - Rust](#backtracestyle-in-std-panic-rust) - [IntErrorKind in std::num - Rust](#interrorkind-in-std-num-rust) - [SeekFrom in std::io - Rust](#seekfrom-in-std-io-rust) - [Shutdown in std::net - Rust](#shutdown-in-std-net-rust) - [VarError in std::env - Rust](#varerror-in-std-env-rust) - [FpCategory in std::num - Rust](#fpcategory-in-std-num-rust) - [ErrorKind in std::io - Rust](#errorkind-in-std-io-rust) - [GetDisjointMutError in std::slice - Rust](#getdisjointmuterror-in-std-slice-rust) - [Ordering in std::sync::atomic - Rust](#ordering-in-std-sync-atomic-rust) - [FromBytesWithNulError in std::ffi - Rust](#frombyteswithnulerror-in-std-ffi-rust) - [Char in std::ascii - Rust](#char-in-std-ascii-rust) - [SearchStep in std::str::pattern - Rust](#searchstep-in-std-str-pattern-rust) - [Ipv6MulticastScope in std::net - Rust](#ipv6multicastscope-in-std-net-rust) - [RecvTimeoutError in std::sync::mpsc - Rust](#recvtimeouterror-in-std-sync-mpsc-rust) - [TryRecvError in std::sync::mpsc - Rust](#tryrecverror-in-std-sync-mpsc-rust) - [IpAddr in std::net - Rust](#ipaddr-in-std-net-rust) - [BinaryHeap in std::collections - Rust](#binaryheap-in-std-collections-rust) - [Ord in std::cmp - Rust](#ord-in-std-cmp-rust) - [PartialOrd in std::cmp - Rust](#partialord-in-std-cmp-rust) - [Eq in std::cmp - Rust](#eq-in-std-cmp-rust) - [RecvError in std::sync::mpsc - Rust](#recverror-in-std-sync-mpsc-rust) - [Duration in std::time - Rust](#duration-in-std-time-rust) - [LazyLock in std::sync - Rust](#lazylock-in-std-sync-rust) - [EncodeUtf16 in std::str - Rust](#encodeutf16-in-std-str-rust) - [Receiver in std::sync::mpsc - Rust](#receiver-in-std-sync-mpsc-rust) --- # Rust Documentation Rust Documentation ================== Welcome to an overview of the documentation provided by the [Rust project](https://www.rust-lang.org/) . This page contains links to various helpful references, most of which are available offline (if opened with `rustup doc`). Many of these resources take the form of “books”; we collectively call these “The Rust Bookshelf.” Some are large, some are small. All of these books are managed by the Rust Organization, but other unofficial documentation resources are included here as well! If you’re just looking for the standard library reference, here it is: [Rust API documentation](https://doc.rust-lang.org/stable/std/index.html) [§](https://doc.rust-lang.org/stable/#learning-rust) Learning Rust ------------------------------------------------------------------ If you’d like to learn Rust, this is the section for you! All of these resources assume that you have programmed before, but not in any specific language: ### [§](https://doc.rust-lang.org/stable/#the-rust-programming-language) The Rust Programming Language Affectionately nicknamed “the book,” [The Rust Programming Language](https://doc.rust-lang.org/stable/book/index.html) will give you an overview of the language from first principles. You’ll build a few projects along the way, and by the end, you’ll have a solid grasp of how to use the language. ### [§](https://doc.rust-lang.org/stable/#rust-by-example) Rust By Example If reading multiple hundreds of pages about a language isn’t your style, then [Rust By Example](https://doc.rust-lang.org/stable/rust-by-example/index.html) has you covered. RBE shows off a bunch of code without using a lot of words. It also includes exercises! ### [§](https://doc.rust-lang.org/stable/#rustlings) Rustlings [Rustlings](https://github.com/rust-lang/rustlings) guides you through downloading and setting up the Rust toolchain, then provides an interactive tool that teaches you how to solve coding challenges in Rust. ### [§](https://doc.rust-lang.org/stable/#rust-playground) Rust Playground The [Rust Playground](https://play.rust-lang.org/) is a great place to try out and share small bits of code, or experiment with some of the most popular crates. [§](https://doc.rust-lang.org/stable/#using-rust) Using Rust ------------------------------------------------------------ Once you’ve gotten familiar with the language, these resources can help you put it to work. ### [§](https://doc.rust-lang.org/stable/#the-standard-library) The Standard Library Rust’s standard library has [extensive API documentation](https://doc.rust-lang.org/stable/std/index.html) , with explanations of how to use various things, as well as example code for accomplishing various tasks. Code examples have a “Run” button on hover that opens the sample in the playground. Search ### [§](https://doc.rust-lang.org/stable/#your-personal-documentation) Your Personal Documentation Whenever you are working in a crate, `cargo doc --open` will generate documentation for your project _and_ all its dependencies in their correct version, and open it in your browser. Add the flag `--document-private-items` to also show items not marked `pub`. ### [§](https://doc.rust-lang.org/stable/#rust-version-history) Rust Version History [The Release Notes](https://doc.rust-lang.org/stable/releases.html) describes the change history of the Rust toolchain and language. [The Edition Guide](https://doc.rust-lang.org/stable/edition-guide/index.html) describes the Rust editions and their differences. The latest version of the toolchain supports all historical editions. ### [§](https://doc.rust-lang.org/stable/#the-rustc-book) The `rustc` Book [The `rustc` Book](https://doc.rust-lang.org/stable/rustc/index.html) describes the Rust compiler, `rustc`. ### [§](https://doc.rust-lang.org/stable/#the-cargo-book) The Cargo Book [The Cargo Book](https://doc.rust-lang.org/stable/cargo/index.html) is a guide to Cargo, Rust’s build tool and dependency manager. ### [§](https://doc.rust-lang.org/stable/#the-rustdoc-book) The Rustdoc Book [The Rustdoc Book](https://doc.rust-lang.org/stable/rustdoc/index.html) describes our documentation tool, `rustdoc`. ### [§](https://doc.rust-lang.org/stable/#the-clippy-book) The Clippy Book [The Clippy Book](https://doc.rust-lang.org/stable/clippy/index.html) describes our static analyzer, Clippy. ### [§](https://doc.rust-lang.org/stable/#extended-error-listing) Extended Error Listing Many of Rust’s errors come with error codes, and you can request extended diagnostics from the compiler on those errors (with `rustc --explain`). You can also read them here if you prefer: [rustc error codes](https://doc.rust-lang.org/stable/error_codes/index.html) [§](https://doc.rust-lang.org/stable/#mastering-rust) Mastering Rust -------------------------------------------------------------------- Once you’re quite familiar with the language, you may find these advanced resources useful. ### [§](https://doc.rust-lang.org/stable/#the-reference) The Reference [The Reference](https://doc.rust-lang.org/stable/reference/index.html) is not a formal spec, but is more detailed and comprehensive than the book. ### [§](https://doc.rust-lang.org/stable/#the-style-guide) The Style Guide [The Rust Style Guide](https://doc.rust-lang.org/stable/style-guide/index.html) describes the standard formatting of Rust code. Most developers use `cargo fmt` to invoke `rustfmt` and format the code automatically (the result matches this style guide). ### [§](https://doc.rust-lang.org/stable/#the-rustonomicon) The Rustonomicon [The Rustonomicon](https://doc.rust-lang.org/stable/nomicon/index.html) is your guidebook to the dark arts of unsafe Rust. It’s also sometimes called “the ’nomicon.” ### [§](https://doc.rust-lang.org/stable/#the-unstable-book) The Unstable Book [The Unstable Book](https://doc.rust-lang.org/stable/unstable-book/index.html) has documentation for unstable features. ### [§](https://doc.rust-lang.org/stable/#the-rustc-development-guide) The `rustc` Development Guide [The `rustc-dev-guide`](https://rustc-dev-guide.rust-lang.org/) documents how the compiler works and how to contribute to it. This is useful if you want to build or modify the Rust compiler from source (e.g. to target something non-standard). [§](https://doc.rust-lang.org/stable/#specialized-rust) Specialized Rust ------------------------------------------------------------------------ When using Rust in specific domains, consider using the following resources tailored to each area. ### [§](https://doc.rust-lang.org/stable/#embedded-systems) Embedded Systems When developing for Bare Metal or Embedded Linux systems, you may find these resources maintained by the [Embedded Working Group](https://github.com/rust-embedded) useful. #### [§](https://doc.rust-lang.org/stable/#the-embedded-rust-book) The Embedded Rust Book [The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/index.html) is targeted at developers familiar with embedded development and familiar with Rust, but have not used Rust for embedded development. --- # std - Rust [Settings](https://doc.rust-lang.org/stable/settings.html) [Help](https://doc.rust-lang.org/stable/help.html) [Crate std](https://doc.rust-lang.org/stable/std/index.html#) -------------------------------------------------------------- [](https://doc.rust-lang.org/stable/std/all.html "show sidebar") Crate std Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/lib.rs.html#1-767) [Search](https://doc.rust-lang.org/stable/std/index.html?search=) [Settings](https://doc.rust-lang.org/stable/settings.html) [Help](https://doc.rust-lang.org/stable/help.html) Summary Expand description [§](https://doc.rust-lang.org/stable/std/index.html#the-rust-standard-library) 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](https://crates.io/) . It offers core types, like [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") and [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , library-defined [operations on language primitives](https://doc.rust-lang.org/stable/std/index.html#primitives) , [standard macros](https://doc.rust-lang.org/stable/std/index.html#macros) , [I/O](https://doc.rust-lang.org/stable/std/io/index.html "mod std::io") and [multithreading](https://doc.rust-lang.org/stable/std/thread/index.html "mod std::thread") , among [many other things](https://doc.rust-lang.org/stable/std/index.html#what-is-in-the-standard-library-documentation) . `std` is available to all Rust crates by default. Therefore, the standard library can be accessed in [`use`](https://doc.rust-lang.org/stable/book/ch07-02-defining-modules-to-control-scope-and-privacy.html) statements through the path `std`, as in [`use std::env`](https://doc.rust-lang.org/stable/std/env/index.html) . [§](https://doc.rust-lang.org/stable/std/index.html#how-to-read-this-documentation) 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](https://doc.rust-lang.org/stable/std/index.html#) at the top of the page. Otherwise, you may want to jump to one of these useful sections: * [`std::*` modules](https://doc.rust-lang.org/stable/std/index.html#modules) * [Primitive types](https://doc.rust-lang.org/stable/std/index.html#primitives) * [Standard macros](https://doc.rust-lang.org/stable/std/index.html#macros) * [The Rust Prelude](https://doc.rust-lang.org/stable/std/prelude/index.html "mod std::prelude") 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. [§](https://doc.rust-lang.org/stable/std/index.html#what-is-in-the-standard-library-documentation) 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](https://doc.rust-lang.org/stable/std/index.html#modules) . These modules are the bedrock upon which all of Rust is forged, and they have mighty names like [`std::slice`](https://doc.rust-lang.org/stable/std/slice/index.html "mod std::slice") and [`std::cmp`](https://doc.rust-lang.org/stable/std/cmp/index.html "mod 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](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html) are documented here. This can be a source of confusion for two reasons: 1. While primitives are implemented by the compiler, the standard library implements methods directly on the primitive types (and it is the only library that does so), which are [documented in the section on primitives](https://doc.rust-lang.org/stable/std/index.html#primitives) . 2. The standard library exports many modules _with the same name as primitive types_. These define additional items related to the primitive type, but not the all-important methods. So for example there is a [page for the primitive type `char`](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") that lists all the methods that can be called on characters (very useful), and there is a [page for the module `std::char`](https://doc.rust-lang.org/stable/std/char/index.html "mod std::char") that documents iterator and error types created by these methods (rarely useful). Note the documentation for the primitives [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") and [`[T]`](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive slice") (also called ‘slice’). Many method calls on [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") and [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") are actually calls to methods on [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") and [`[T]`](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive slice") respectively, via [deref coercions](https://doc.rust-lang.org/stable/book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods) . Third, the standard library defines [The Rust Prelude](https://doc.rust-lang.org/stable/std/prelude/index.html "mod std::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](https://doc.rust-lang.org/stable/std/index.html#macros) (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. [§](https://doc.rust-lang.org/stable/std/index.html#contributing-changes-to-the-documentation) Contributing changes to the documentation ---------------------------------------------------------------------------------------------------------------------------------------- Check out the Rust contribution guidelines [here](https://rustc-dev-guide.rust-lang.org/contributing.html#writing-documentation) . The source for this documentation can be found on [GitHub](https://github.com/rust-lang/rust) 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](https://rust-lang.zulipchat.com/) #docs. [§](https://doc.rust-lang.org/stable/std/index.html#a-tour-of-the-rust-standard-library) 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. ### [§](https://doc.rust-lang.org/stable/std/index.html#containers-and-collections) Containers and collections The [`option`](https://doc.rust-lang.org/stable/std/option/index.html "mod std::option") and [`result`](https://doc.rust-lang.org/stable/std/result/index.html "mod std::result") modules define optional and error-handling types, [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") and [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . The [`iter`](https://doc.rust-lang.org/stable/std/iter/index.html "mod std::iter") module defines Rust’s iterator trait, [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , which works with the [`for`](https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#looping-through-a-collection-with-for) loop to access collections. The standard library exposes three common ways to deal with contiguous regions of memory: * [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") - A heap-allocated _vector_ that is resizable at runtime. * [`[T; N]`](https://doc.rust-lang.org/stable/std/primitive.array.html "primitive array") - An inline _array_ with a fixed size at compile time. * [`[T]`](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive slice") - A dynamically sized _slice_ into any other kind of contiguous storage, 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]>`](https://doc.rust-lang.org/stable/std/boxed/index.html "mod std::boxed") - _owned slice_ [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") , a UTF-8 string slice, is a primitive type, and the standard library defines many methods for it. Rust [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") s are typically accessed as immutable references: `&str`. Use the owned [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") for building and mutating strings. For converting to strings use the [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") macro, and for converting from strings use the [`FromStr`](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html "trait std::str::FromStr") trait. Data may be shared by placing it in a reference-counted box or the [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") type, and if further contained in a [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") or [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") , may be mutated as well as shared. Likewise, in a concurrent setting it is common to pair an atomically-reference-counted box, [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") , with a [`Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html "struct std::sync::Mutex") to get the same effect. The [`collections`](https://doc.rust-lang.org/stable/std/collections/index.html "mod std::collections") module defines maps, sets, linked lists and other typical collection types, including the common [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") . ### [§](https://doc.rust-lang.org/stable/std/index.html#platform-abstractions-and-io) 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](https://doc.rust-lang.org/stable/std/fs/struct.File.html "struct std::fs::File") , [TCP](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") , and [UDP](https://doc.rust-lang.org/stable/std/net/struct.UdpSocket.html "struct std::net::UdpSocket") , are defined in the [`io`](https://doc.rust-lang.org/stable/std/io/index.html "mod std::io") , [`fs`](https://doc.rust-lang.org/stable/std/fs/index.html "mod std::fs") , and [`net`](https://doc.rust-lang.org/stable/std/net/index.html "mod std::net") modules. The [`thread`](https://doc.rust-lang.org/stable/std/thread/index.html "mod std::thread") module contains Rust’s threading abstractions. [`sync`](https://doc.rust-lang.org/stable/std/sync/index.html "mod std::sync") contains further primitive shared memory types, including [`atomic`](https://doc.rust-lang.org/stable/std/sync/atomic/index.html "mod std::sync::atomic") , [`mpmc`](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html "mod std::sync::mpmc") and [`mpsc`](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html "mod std::sync::mpsc") , which contains the channel types for message passing. [§](https://doc.rust-lang.org/stable/std/index.html#use-before-and-after-main) 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: * [`thread::current()`](https://doc.rust-lang.org/stable/std/thread/fn.current.html "fn std::thread::current") * 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) Primitive Types[§](https://doc.rust-lang.org/stable/std/index.html#primitives) ------------------------------------------------------------------------------- [array](https://doc.rust-lang.org/stable/std/primitive.array.html "primitive std::array") A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the non-negative compile-time constant size, `N`. [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive std::bool") The boolean type. [char](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive std::char") A character type. [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html "primitive std::f32") A 32-bit floating-point type (specifically, the “binary32” type defined in IEEE 754-2008). [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html "primitive std::f64") A 64-bit floating-point type (specifically, the “binary64” type defined in IEEE 754-2008). [fn](https://doc.rust-lang.org/stable/std/primitive.fn.html "primitive std::fn") Function pointers, like `fn(usize) -> bool`. [i8](https://doc.rust-lang.org/stable/std/primitive.i8.html "primitive std::i8") The 8-bit signed integer type. [i16](https://doc.rust-lang.org/stable/std/primitive.i16.html "primitive std::i16") The 16-bit signed integer type. [i32](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive std::i32") The 32-bit signed integer type. [i64](https://doc.rust-lang.org/stable/std/primitive.i64.html "primitive std::i64") The 64-bit signed integer type. [i128](https://doc.rust-lang.org/stable/std/primitive.i128.html "primitive std::i128") The 128-bit signed integer type. [isize](https://doc.rust-lang.org/stable/std/primitive.isize.html "primitive std::isize") The pointer-sized signed integer type. [pointer](https://doc.rust-lang.org/stable/std/primitive.pointer.html "primitive std::pointer") Raw, unsafe pointers, `*const T`, and `*mut T`. [reference](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive std::reference") References, `&T` and `&mut T`. [slice](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive std::slice") A dynamically-sized view into a contiguous sequence, `[T]`. [str](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive std::str") String slices. [tuple](https://doc.rust-lang.org/stable/std/primitive.tuple.html "primitive std::tuple") A finite heterogeneous sequence, `(T, U, ..)`. [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive std::u8") The 8-bit unsigned integer type. [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive std::u16") The 16-bit unsigned integer type. [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html "primitive std::u32") The 32-bit unsigned integer type. [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html "primitive std::u64") The 64-bit unsigned integer type. [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html "primitive std::u128") The 128-bit unsigned integer type. [unit](https://doc.rust-lang.org/stable/std/primitive.unit.html "primitive std::unit") The `()` type, also called “unit”. [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive std::usize") The pointer-sized unsigned integer type. [f16](https://doc.rust-lang.org/stable/std/primitive.f16.html "primitive std::f16") Experimental A 16-bit floating-point type (specifically, the “binary16” type defined in IEEE 754-2008). [f128](https://doc.rust-lang.org/stable/std/primitive.f128.html "primitive std::f128") Experimental A 128-bit floating-point type (specifically, the “binary128” type defined in IEEE 754-2008). [never](https://doc.rust-lang.org/stable/std/primitive.never.html "primitive std::never") Experimental The `!` type, also called “never”. Modules[§](https://doc.rust-lang.org/stable/std/index.html#modules) -------------------------------------------------------------------- [alloc](https://doc.rust-lang.org/stable/std/alloc/index.html "mod std::alloc") Memory allocation APIs. [any](https://doc.rust-lang.org/stable/std/any/index.html "mod std::any") Utilities for dynamic typing or type reflection. [arch](https://doc.rust-lang.org/stable/std/arch/index.html "mod std::arch") SIMD and vendor intrinsics module. [array](https://doc.rust-lang.org/stable/std/array/index.html "mod std::array") Utilities for the array primitive type. [ascii](https://doc.rust-lang.org/stable/std/ascii/index.html "mod std::ascii") Operations on ASCII strings and characters. [backtrace](https://doc.rust-lang.org/stable/std/backtrace/index.html "mod std::backtrace") Support for capturing a stack backtrace of an OS thread [borrow](https://doc.rust-lang.org/stable/std/borrow/index.html "mod std::borrow") A module for working with borrowed data. [boxed](https://doc.rust-lang.org/stable/std/boxed/index.html "mod std::boxed") The `Box` type for heap allocation. [cell](https://doc.rust-lang.org/stable/std/cell/index.html "mod std::cell") Shareable mutable containers. [char](https://doc.rust-lang.org/stable/std/char/index.html "mod std::char") Utilities for the `char` primitive type. [clone](https://doc.rust-lang.org/stable/std/clone/index.html "mod std::clone") The `Clone` trait for types that cannot be ‘implicitly copied’. [cmp](https://doc.rust-lang.org/stable/std/cmp/index.html "mod std::cmp") Utilities for comparing and ordering values. [collections](https://doc.rust-lang.org/stable/std/collections/index.html "mod std::collections") Collection types. [convert](https://doc.rust-lang.org/stable/std/convert/index.html "mod std::convert") Traits for conversions between types. [default](https://doc.rust-lang.org/stable/std/default/index.html "mod std::default") The `Default` trait for types with a default value. [env](https://doc.rust-lang.org/stable/std/env/index.html "mod std::env") Inspection and manipulation of the process’s environment. [error](https://doc.rust-lang.org/stable/std/error/index.html "mod std::error") Interfaces for working with Errors. [f32](https://doc.rust-lang.org/stable/std/f32/index.html "mod std::f32") Constants for the `f32` single-precision floating point type. [f64](https://doc.rust-lang.org/stable/std/f64/index.html "mod std::f64") Constants for the `f64` double-precision floating point type. [ffi](https://doc.rust-lang.org/stable/std/ffi/index.html "mod std::ffi") Utilities related to FFI bindings. [fmt](https://doc.rust-lang.org/stable/std/fmt/index.html "mod std::fmt") Utilities for formatting and printing `String`s. [fs](https://doc.rust-lang.org/stable/std/fs/index.html "mod std::fs") Filesystem manipulation operations. [future](https://doc.rust-lang.org/stable/std/future/index.html "mod std::future") Asynchronous basic functionality. [hash](https://doc.rust-lang.org/stable/std/hash/index.html "mod std::hash") Generic hashing support. [hint](https://doc.rust-lang.org/stable/std/hint/index.html "mod std::hint") Hints to compiler that affects how code should be emitted or optimized. [i8](https://doc.rust-lang.org/stable/std/i8/index.html "mod std::i8") Deprecation planned Redundant constants module for the [`i8` primitive type](https://doc.rust-lang.org/stable/std/primitive.i8.html "primitive i8") . [i16](https://doc.rust-lang.org/stable/std/i16/index.html "mod std::i16") Deprecation planned Redundant constants module for the [`i16` primitive type](https://doc.rust-lang.org/stable/std/primitive.i16.html "primitive i16") . [i32](https://doc.rust-lang.org/stable/std/i32/index.html "mod std::i32") Deprecation planned Redundant constants module for the [`i32` primitive type](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive i32") . [i64](https://doc.rust-lang.org/stable/std/i64/index.html "mod std::i64") Deprecation planned Redundant constants module for the [`i64` primitive type](https://doc.rust-lang.org/stable/std/primitive.i64.html "primitive i64") . [i128](https://doc.rust-lang.org/stable/std/i128/index.html "mod std::i128") Deprecation planned Redundant constants module for the [`i128` primitive type](https://doc.rust-lang.org/stable/std/primitive.i128.html "primitive i128") . [io](https://doc.rust-lang.org/stable/std/io/index.html "mod std::io") Traits, helpers, and type definitions for core I/O functionality. [isize](https://doc.rust-lang.org/stable/std/isize/index.html "mod std::isize") Deprecation planned Redundant constants module for the [`isize` primitive type](https://doc.rust-lang.org/stable/std/primitive.isize.html "primitive isize") . [iter](https://doc.rust-lang.org/stable/std/iter/index.html "mod std::iter") Composable external iteration. [marker](https://doc.rust-lang.org/stable/std/marker/index.html "mod std::marker") Primitive traits and types representing basic properties of types. [mem](https://doc.rust-lang.org/stable/std/mem/index.html "mod std::mem") Basic functions for dealing with memory. [net](https://doc.rust-lang.org/stable/std/net/index.html "mod std::net") Networking primitives for TCP/UDP communication. [num](https://doc.rust-lang.org/stable/std/num/index.html "mod std::num") Additional functionality for numerics. [ops](https://doc.rust-lang.org/stable/std/ops/index.html "mod std::ops") Overloadable operators. [option](https://doc.rust-lang.org/stable/std/option/index.html "mod std::option") Optional values. [os](https://doc.rust-lang.org/stable/std/os/index.html "mod std::os") OS-specific functionality. [panic](https://doc.rust-lang.org/stable/std/panic/index.html "mod std::panic") Panic support in the standard library. [path](https://doc.rust-lang.org/stable/std/path/index.html "mod std::path") Cross-platform path manipulation. [pin](https://doc.rust-lang.org/stable/std/pin/index.html "mod std::pin") Types that pin data to a location in memory. [prelude](https://doc.rust-lang.org/stable/std/prelude/index.html "mod std::prelude") The Rust Prelude [primitive](https://doc.rust-lang.org/stable/std/primitive/index.html "mod std::primitive") This module reexports the primitive types to allow usage that is not possibly shadowed by other declared types. [process](https://doc.rust-lang.org/stable/std/process/index.html "mod std::process") A module for working with processes. [ptr](https://doc.rust-lang.org/stable/std/ptr/index.html "mod std::ptr") Manually manage memory through raw pointers. [rc](https://doc.rust-lang.org/stable/std/rc/index.html "mod std::rc") Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’. [result](https://doc.rust-lang.org/stable/std/result/index.html "mod std::result") Error handling with the `Result` type. [slice](https://doc.rust-lang.org/stable/std/slice/index.html "mod std::slice") Utilities for the slice primitive type. [str](https://doc.rust-lang.org/stable/std/str/index.html "mod std::str") Utilities for the `str` primitive type. [string](https://doc.rust-lang.org/stable/std/string/index.html "mod std::string") A UTF-8–encoded, growable string. [sync](https://doc.rust-lang.org/stable/std/sync/index.html "mod std::sync") Useful synchronization primitives. [task](https://doc.rust-lang.org/stable/std/task/index.html "mod std::task") Types and Traits for working with asynchronous tasks. [thread](https://doc.rust-lang.org/stable/std/thread/index.html "mod std::thread") Native threads. [time](https://doc.rust-lang.org/stable/std/time/index.html "mod std::time") Temporal quantification. [u8](https://doc.rust-lang.org/stable/std/u8/index.html "mod std::u8") Deprecation planned Redundant constants module for the [`u8` primitive type](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") . [u16](https://doc.rust-lang.org/stable/std/u16/index.html "mod std::u16") Deprecation planned Redundant constants module for the [`u16` primitive type](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive u16") . [u32](https://doc.rust-lang.org/stable/std/u32/index.html "mod std::u32") Deprecation planned Redundant constants module for the [`u32` primitive type](https://doc.rust-lang.org/stable/std/primitive.u32.html "primitive u32") . [u64](https://doc.rust-lang.org/stable/std/u64/index.html "mod std::u64") Deprecation planned Redundant constants module for the [`u64` primitive type](https://doc.rust-lang.org/stable/std/primitive.u64.html "primitive u64") . [u128](https://doc.rust-lang.org/stable/std/u128/index.html "mod std::u128") Deprecation planned Redundant constants module for the [`u128` primitive type](https://doc.rust-lang.org/stable/std/primitive.u128.html "primitive u128") . [usize](https://doc.rust-lang.org/stable/std/usize/index.html "mod std::usize") Deprecation planned Redundant constants module for the [`usize` primitive type](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") . [vec](https://doc.rust-lang.org/stable/std/vec/index.html "mod std::vec") A contiguous growable array type with heap-allocated contents, written `Vec`. [assert\_matches](https://doc.rust-lang.org/stable/std/assert_matches/index.html "mod std::assert_matches") Experimental Unstable module containing the unstable `assert_matches` macro. [async\_iter](https://doc.rust-lang.org/stable/std/async_iter/index.html "mod std::async_iter") Experimental Composable asynchronous iteration. [autodiff](https://doc.rust-lang.org/stable/std/autodiff/index.html "mod std::autodiff") Experimental This module provides support for automatic differentiation. [bstr](https://doc.rust-lang.org/stable/std/bstr/index.html "mod std::bstr") Experimental The `ByteStr` and `ByteString` types and trait implementations. [f16](https://doc.rust-lang.org/stable/std/f16/index.html "mod std::f16") Experimental Constants for the `f16` half-precision floating point type. [f128](https://doc.rust-lang.org/stable/std/f128/index.html "mod std::f128") Experimental Constants for the `f128` quadruple-precision floating point type. [from](https://doc.rust-lang.org/stable/std/from/index.html "mod std::from") Experimental Unstable module containing the unstable `From` derive macro. [intrinsics](https://doc.rust-lang.org/stable/std/intrinsics/index.html "mod std::intrinsics") Experimental Compiler intrinsics. [pat](https://doc.rust-lang.org/stable/std/pat/index.html "mod std::pat") Experimental Helper module for exporting the `pattern_type` macro [random](https://doc.rust-lang.org/stable/std/random/index.html "mod std::random") Experimental Random value generation. [range](https://doc.rust-lang.org/stable/std/range/index.html "mod std::range") Experimental Experimental replacement range types [simd](https://doc.rust-lang.org/stable/std/simd/index.html "mod std::simd") Experimental Portable SIMD module. [unsafe\_binder](https://doc.rust-lang.org/stable/std/unsafe_binder/index.html "mod std::unsafe_binder") Experimental Operators used to turn types into unsafe binders and back. Macros[§](https://doc.rust-lang.org/stable/std/index.html#macros) ------------------------------------------------------------------ [assert](https://doc.rust-lang.org/stable/std/macro.assert.html "macro std::assert") Asserts that a boolean expression is `true` at runtime. [assert\_eq](https://doc.rust-lang.org/stable/std/macro.assert_eq.html "macro std::assert_eq") Asserts that two expressions are equal to each other (using [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") ). [assert\_ne](https://doc.rust-lang.org/stable/std/macro.assert_ne.html "macro std::assert_ne") Asserts that two expressions are not equal to each other (using [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") ). [cfg](https://doc.rust-lang.org/stable/std/macro.cfg.html "macro std::cfg") Evaluates boolean combinations of configuration flags at compile-time. [column](https://doc.rust-lang.org/stable/std/macro.column.html "macro std::column") Expands to the column number at which it was invoked. [compile\_error](https://doc.rust-lang.org/stable/std/macro.compile_error.html "macro std::compile_error") Causes compilation to fail with the given error message when encountered. [concat](https://doc.rust-lang.org/stable/std/macro.concat.html "macro std::concat") Concatenates literals into a static string slice. [dbg](https://doc.rust-lang.org/stable/std/macro.dbg.html "macro std::dbg") Prints and returns the value of a given expression for quick and dirty debugging. [debug\_assert](https://doc.rust-lang.org/stable/std/macro.debug_assert.html "macro std::debug_assert") Asserts that a boolean expression is `true` at runtime. [debug\_assert\_eq](https://doc.rust-lang.org/stable/std/macro.debug_assert_eq.html "macro std::debug_assert_eq") Asserts that two expressions are equal to each other. [debug\_assert\_ne](https://doc.rust-lang.org/stable/std/macro.debug_assert_ne.html "macro std::debug_assert_ne") Asserts that two expressions are not equal to each other. [env](https://doc.rust-lang.org/stable/std/macro.env.html "macro std::env") Inspects an environment variable at compile time. [eprint](https://doc.rust-lang.org/stable/std/macro.eprint.html "macro std::eprint") Prints to the standard error. [eprintln](https://doc.rust-lang.org/stable/std/macro.eprintln.html "macro std::eprintln") Prints to the standard error, with a newline. [file](https://doc.rust-lang.org/stable/std/macro.file.html "macro std::file") Expands to the file name in which it was invoked. [format](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") Creates a `String` using interpolation of runtime expressions. [format\_args](https://doc.rust-lang.org/stable/std/macro.format_args.html "macro std::format_args") Constructs parameters for the other string-formatting macros. [include](https://doc.rust-lang.org/stable/std/macro.include.html "macro std::include") Parses a file as an expression or an item according to the context. [include\_bytes](https://doc.rust-lang.org/stable/std/macro.include_bytes.html "macro std::include_bytes") Includes a file as a reference to a byte array. [include\_str](https://doc.rust-lang.org/stable/std/macro.include_str.html "macro std::include_str") Includes a UTF-8 encoded file as a string. [is\_x86\_feature\_detected](https://doc.rust-lang.org/stable/std/macro.is_x86_feature_detected.html "macro std::is_x86_feature_detected") A macro to test at _runtime_ whether a CPU feature is available on x86/x86-64 platforms. [line](https://doc.rust-lang.org/stable/std/macro.line.html "macro std::line") Expands to the line number on which it was invoked. [matches](https://doc.rust-lang.org/stable/std/macro.matches.html "macro std::matches") Returns whether the given expression matches the provided pattern. [module\_path](https://doc.rust-lang.org/stable/std/macro.module_path.html "macro std::module_path") Expands to a string that represents the current module path. [option\_env](https://doc.rust-lang.org/stable/std/macro.option_env.html "macro std::option_env") Optionally inspects an environment variable at compile time. [panic](https://doc.rust-lang.org/stable/std/macro.panic.html "macro std::panic") Panics the current thread. [print](https://doc.rust-lang.org/stable/std/macro.print.html "macro std::print") Prints to the standard output. [println](https://doc.rust-lang.org/stable/std/macro.println.html "macro std::println") Prints to the standard output, with a newline. [stringify](https://doc.rust-lang.org/stable/std/macro.stringify.html "macro std::stringify") Stringifies its arguments. [thread\_local](https://doc.rust-lang.org/stable/std/macro.thread_local.html "macro std::thread_local") Declare a new thread local storage key of type [`std::thread::LocalKey`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") . [todo](https://doc.rust-lang.org/stable/std/macro.todo.html "macro std::todo") Indicates unfinished code. [try](https://doc.rust-lang.org/stable/std/macro.try.html "macro std::try") Deprecated Unwraps a result or propagates its error. [unimplemented](https://doc.rust-lang.org/stable/std/macro.unimplemented.html "macro std::unimplemented") Indicates unimplemented code by panicking with a message of “not implemented”. [unreachable](https://doc.rust-lang.org/stable/std/macro.unreachable.html "macro std::unreachable") Indicates unreachable code. [vec](https://doc.rust-lang.org/stable/std/macro.vec.html "macro std::vec") Creates a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") containing the arguments. [write](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") Writes formatted data into a buffer. [writeln](https://doc.rust-lang.org/stable/std/macro.writeln.html "macro std::writeln") Writes formatted data into a buffer, with a newline appended. [cfg\_select](https://doc.rust-lang.org/stable/std/macro.cfg_select.html "macro std::cfg_select") Experimental Selects code at compile-time based on `cfg` predicates. [concat\_bytes](https://doc.rust-lang.org/stable/std/macro.concat_bytes.html "macro std::concat_bytes") Experimental Concatenates literals into a byte slice. [const\_format\_args](https://doc.rust-lang.org/stable/std/macro.const_format_args.html "macro std::const_format_args") Experimental Same as [`format_args`](https://doc.rust-lang.org/stable/std/macro.format_args.html "macro std::format_args") , but can be used in some const contexts. [log\_syntax](https://doc.rust-lang.org/stable/std/macro.log_syntax.html "macro std::log_syntax") Experimental Prints passed tokens into the standard output. [trace\_macros](https://doc.rust-lang.org/stable/std/macro.trace_macros.html "macro std::trace_macros") Experimental Enables or disables tracing functionality used for debugging other macros. Keywords[§](https://doc.rust-lang.org/stable/std/index.html#keywords) ---------------------------------------------------------------------- [SelfTy](https://doc.rust-lang.org/stable/std/keyword.SelfTy.html "keyword std::SelfTy") The implementing type within a [`trait`](https://doc.rust-lang.org/stable/std/keyword.trait.html) or [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) block, or the current type within a type definition. [as](https://doc.rust-lang.org/stable/std/keyword.as.html "keyword std::as") Cast between types, rename an import, or qualify paths to associated items. [async](https://doc.rust-lang.org/stable/std/keyword.async.html "keyword std::async") Returns a [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") instead of blocking the current thread. [await](https://doc.rust-lang.org/stable/std/keyword.await.html "keyword std::await") Suspend execution until the result of a [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") is ready. [become](https://doc.rust-lang.org/stable/std/keyword.become.html "keyword std::become") Perform a tail-call of a function. [break](https://doc.rust-lang.org/stable/std/keyword.break.html "keyword std::break") Exit early from a loop or labelled block. [const](https://doc.rust-lang.org/stable/std/keyword.const.html "keyword std::const") Compile-time constants, compile-time blocks, compile-time evaluable functions, and raw pointers. [continue](https://doc.rust-lang.org/stable/std/keyword.continue.html "keyword std::continue") Skip to the next iteration of a loop. [crate](https://doc.rust-lang.org/stable/std/keyword.crate.html "keyword std::crate") A Rust binary or library. [dyn](https://doc.rust-lang.org/stable/std/keyword.dyn.html "keyword std::dyn") `dyn` is a prefix of a [trait object](https://doc.rust-lang.org/stable/book/ch17-02-trait-objects.html) ’s type. [else](https://doc.rust-lang.org/stable/std/keyword.else.html "keyword std::else") What expression to evaluate when an [`if`](https://doc.rust-lang.org/stable/std/keyword.if.html) condition evaluates to [`false`](https://doc.rust-lang.org/stable/std/keyword.false.html) . [enum](https://doc.rust-lang.org/stable/std/keyword.enum.html "keyword std::enum") A type that can be any one of several variants. [extern](https://doc.rust-lang.org/stable/std/keyword.extern.html "keyword std::extern") Link to or import external code. [false](https://doc.rust-lang.org/stable/std/keyword.false.html "keyword std::false") A value of type [`bool`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") representing logical **false**. [fn](https://doc.rust-lang.org/stable/std/keyword.fn.html "keyword std::fn") A function or function pointer. [for](https://doc.rust-lang.org/stable/std/keyword.for.html "keyword std::for") Iteration with [`in`](https://doc.rust-lang.org/stable/std/keyword.in.html) , trait implementation with [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) , or [higher-ranked trait bounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#higher-ranked-trait-bounds) (`for<'a>`). [if](https://doc.rust-lang.org/stable/std/keyword.if.html "keyword std::if") Evaluate a block if a condition holds. [impl](https://doc.rust-lang.org/stable/std/keyword.impl.html "keyword std::impl") Implementations of functionality for a type, or a type implementing some functionality. [in](https://doc.rust-lang.org/stable/std/keyword.in.html "keyword std::in") Iterate over a series of values with [`for`](https://doc.rust-lang.org/stable/std/keyword.for.html) . [let](https://doc.rust-lang.org/stable/std/keyword.let.html "keyword std::let") Bind a value to a variable. [loop](https://doc.rust-lang.org/stable/std/keyword.loop.html "keyword std::loop") Loop indefinitely. [match](https://doc.rust-lang.org/stable/std/keyword.match.html "keyword std::match") Control flow based on pattern matching. [mod](https://doc.rust-lang.org/stable/std/keyword.mod.html "keyword std::mod") Organize code into [modules](https://doc.rust-lang.org/stable/reference/items/modules.html) . [move](https://doc.rust-lang.org/stable/std/keyword.move.html "keyword std::move") Capture a [closure](https://doc.rust-lang.org/stable/book/ch13-01-closures.html) ’s environment by value. [mut](https://doc.rust-lang.org/stable/std/keyword.mut.html "keyword std::mut") A mutable variable, reference, or pointer. [pub](https://doc.rust-lang.org/stable/std/keyword.pub.html "keyword std::pub") Make an item visible to others. [ref](https://doc.rust-lang.org/stable/std/keyword.ref.html "keyword std::ref") Bind by reference during pattern matching. [return](https://doc.rust-lang.org/stable/std/keyword.return.html "keyword std::return") Returns a value from a function. [self](https://doc.rust-lang.org/stable/std/keyword.self.html "keyword std::self") The receiver of a method, or the current module. [static](https://doc.rust-lang.org/stable/std/keyword.static.html "keyword std::static") A static item is a value which is valid for the entire duration of your program (a `'static` lifetime). [struct](https://doc.rust-lang.org/stable/std/keyword.struct.html "keyword std::struct") A type that is composed of other types. [super](https://doc.rust-lang.org/stable/std/keyword.super.html "keyword std::super") The parent of the current [module](https://doc.rust-lang.org/stable/reference/items/modules.html) . [trait](https://doc.rust-lang.org/stable/std/keyword.trait.html "keyword std::trait") A common interface for a group of types. [true](https://doc.rust-lang.org/stable/std/keyword.true.html "keyword std::true") A value of type [`bool`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") representing logical **true**. [type](https://doc.rust-lang.org/stable/std/keyword.type.html "keyword std::type") Define an [alias](https://doc.rust-lang.org/stable/reference/items/type-aliases.html) for an existing type. [union](https://doc.rust-lang.org/stable/std/keyword.union.html "keyword std::union") The [Rust equivalent of a C-style union](https://doc.rust-lang.org/stable/reference/items/unions.html) . [unsafe](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword std::unsafe") Code or interfaces whose [memory safety](https://doc.rust-lang.org/stable/book/ch19-01-unsafe-rust.html) cannot be verified by the type system. [use](https://doc.rust-lang.org/stable/std/keyword.use.html "keyword std::use") Import or rename items from other crates or modules, use values under ergonomic clones semantic, or specify precise capturing with `use<..>`. [where](https://doc.rust-lang.org/stable/std/keyword.where.html "keyword std::where") Add constraints that must be upheld to use an item. [while](https://doc.rust-lang.org/stable/std/keyword.while.html "keyword std::while") Loop while a condition is upheld. --- # The Rust Programming Language - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") _by Steve Klabnik, Carol Nichols, and Chris Krycho, with contributions from the Rust Community_ This version of the text assumes you’re using Rust 1.85.0 (released 2025-02-17) or later with `edition = "2024"` in the _Cargo.toml_ file of all projects to configure them to use Rust 2024 Edition idioms. See the [“Installation” section of Chapter 1](https://doc.rust-lang.org/stable/book/ch01-01-installation.html) for instructions on installing or updating Rust, and see [Appendix E](https://doc.rust-lang.org/stable/book/appendix-05-editions.html) for information on editions. The HTML format is available online at [https://doc.rust-lang.org/stable/book/](https://doc.rust-lang.org/stable/book/) and offline with installations of Rust made with `rustup`; run `rustup doc --book` to open. Several community [translations](https://doc.rust-lang.org/stable/book/appendix-06-translation.html) are also available. This text is available in [paperback and ebook format from No Starch Press](https://nostarch.com/rust-programming-language-3rd-edition) . > **🚨 Want a more interactive learning experience? Try out a different version of the Rust Book, featuring: quizzes, highlighting, visualizations, and more**: [https://rust-book.cs.brown.edu](https://rust-book.cs.brown.edu/) --- # Introduction - The Rust Edition Guide Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Edition Guide ====================== [](https://doc.rust-lang.org/stable/edition-guide/print.html "Print this book") [](https://github.com/rust-lang/edition-guide "Git repository") [](https://github.com/rust-lang/edition-guide/edit/master/src/introduction.md "Suggest an edit") Welcome to The Rust Edition Guide! "Editions" are Rust's way of introducing changes into the language that would not otherwise be backwards compatible. In this guide, we'll discuss: * What editions are * Which changes are contained in each edition * How to migrate your code from one edition to another --- # Introduction - The Rust Style Guide Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Style Guide ==================== [](https://doc.rust-lang.org/stable/style-guide/print.html "Print this book") [](https://github.com/rust-lang/rust/tree/HEAD/src/doc/style-guide/ "Git repository") Formatting code is a mostly mechanical task which takes both time and mental effort. By using an automatic formatting tool, a programmer is relieved of this task and can concentrate on more important things. Furthermore, by sticking to an established style guide (such as this one), programmers don't need to formulate ad hoc style rules, nor do they need to debate with other programmers what style rules should be used, saving time, communication overhead, and mental energy. Humans comprehend information through pattern matching. By ensuring that all Rust code has similar formatting, less mental effort is required to comprehend a new project, lowering the barrier to entry for new developers. Thus, there are productivity benefits to using a formatting tool (such as `rustfmt`), and even larger benefits by using a community-consistent formatting, typically by using a formatting tool's default settings. The Rust Style Guide defines the default Rust style, and _recommends_ that developers and tools follow the default Rust style. Tools such as `rustfmt` use the style guide as a reference for the default style. Everything in this style guide, whether or not it uses language such as "must" or the imperative mood such as "insert a space ..." or "break the line after ...", refers to the default style. This should not be interpreted as forbidding developers from following a non-default style, or forbidding tools from adding any particular configuration options. If the style guide differs from rustfmt, that may represent a bug in rustfmt, or a bug in the style guide; either way, please report it to the style team or the rustfmt team or both, for investigation and fix. If implementing a new formatting tool based on the style guide and default Rust style, please test it on the corpus of existing Rust code, and avoid causing widespread breakage. The implementation and testing of such a tool may surface bugs in either the style guide or rustfmt, as well as bugs in the tool itself. We typically resolve bugs in a fashion that avoids widespread breakage. * Use spaces, not tabs. * Each level of indentation must be 4 spaces (that is, all indentation outside of string literals and comments must be a multiple of 4). * The maximum width for a line is 100 characters. Prefer block indent over visual indent: `#![allow(unused)] fn main() { // Block indent a_function_call( foo, bar, ); // Visual indent a_function_call(foo, bar); }` This makes for smaller diffs (e.g., if `a_function_call` is renamed in the above example) and less rightward drift. In comma-separated lists of any kind, use a trailing comma when followed by a newline: `#![allow(unused)] fn main() { function_call( argument, another_argument, ); let array = [ element, another_element, yet_another_element, ]; }` This makes moving code (e.g., by copy and paste) easier, and makes diffs smaller, as appending or removing items does not require modifying another line to add or remove a comma. Separate items and statements by either zero or one blank lines (i.e., one or two newlines). E.g, `#![allow(unused)] fn main() { fn foo() { let x = ...; let y = ...; let z = ...; } fn bar() {} fn baz() {} }` Do not include trailing whitespace on the end of any line. This includes blank lines, comment lines, code lines, and string literals. Note that avoiding trailing whitespace in string literals requires care to preserve the value of the literal. In various cases, the default Rust style specifies to sort things. If not otherwise specified, such sorting should be "version sorting", which ensures that (for instance) `x8` comes before `x16` even though the character `1` comes before the character `8`. For the purposes of the Rust style, to compare two strings for version-sorting: * Process both strings from beginning to end as two sequences of maximal-length chunks, where each chunk consists either of a sequence of characters other than ASCII digits, or a sequence of ASCII digits (a numeric chunk), and compare corresponding chunks from the strings. * To compare two numeric chunks, compare them by numeric value, ignoring leading zeroes. If the two chunks have equal numeric value, but different numbers of leading digits, and this is the first time this has happened for these strings, treat the chunks as equal (moving on to the next chunk) but remember which string had more leading zeroes. * To compare two chunks if both are not numeric, compare them by Unicode character lexicographically, with two exceptions: * `_` (underscore) sorts immediately after (space) but before any other character. (This treats underscore as a word separator, as commonly used in identifiers.) * Unless otherwise specified, version-sorting should sort non-lowercase characters (characters that can start an `UpperCamelCase` identifier) before lowercase characters. * If the comparison reaches the end of the string and considers each pair of chunks equal: * If one of the numeric comparisons noted the earliest point at which one string had more leading zeroes than the other, sort the string with more leading zeroes first. * Otherwise, the strings are equal. Note that there exist various algorithms called "version sorting", which generally try to solve the same problem, but which differ in various ways (such as in their handling of numbers with leading zeroes). This algorithm does not purport to precisely match the behavior of any particular other algorithm, only to produce a simple and satisfying result for Rust formatting. In particular, this algorithm aims to produce a satisfying result for a set of symbols that have the same number of leading zeroes, and an acceptable and easily understandable result for a set of symbols that has varying numbers of leading zeroes. As an example, version-sorting will sort the following strings in the order given: * `_ZYXW` * `_abcd` * `A2` * `ABCD` * `Z_YXW` * `ZY_XW` * `ZY_XW` * `ZYXW` * `ZYXW_` * `a1` * `abcd` * `u_zzz` * `u8` * `u16` * `u32` * `u64` * `u128` * `u256` * `ua` * `usize` * `uz` * `v000` * `v00` * `v0` * `v0s` * `v00t` * `v0u` * `v001` * `v01` * `v1` * `v009` * `v09` * `v9` * `v010` * `v10` * `w005s09t` * `w5s009t` * `x64` * `x86` * `x86_32` * `x86_64` * `x86_128` * `x87` * `zyxw` ### [Module-level items](https://doc.rust-lang.org/stable/style-guide/items.html) ### [Statements](https://doc.rust-lang.org/stable/style-guide/statements.html) ### [Expressions](https://doc.rust-lang.org/stable/style-guide/expressions.html) ### [Types](https://doc.rust-lang.org/stable/style-guide/types.html) The following guidelines for comments are recommendations only, a mechanical formatter might skip formatting of comments. Prefer line comments (`//`) to block comments (`/* ... */`). When using line comments, put a single space after the opening sigil. When using single-line block comments, put a single space after the opening sigil and before the closing sigil. For multi-line block comments, put a newline after the opening sigil, and a newline before the closing sigil. Prefer to put a comment on its own line. Where a comment follows code, put a single space before it. Where a block comment appears inline, use surrounding whitespace as if it were an identifier or keyword. Examples: `#![allow(unused)] fn main() { // A comment on an item. struct Foo { ... } fn foo() {} // A comment after an item. pub fn foo(/* a comment before an argument */ x: T) {...} }` Comments should usually be complete sentences. Start with a capital letter, end with a period (`.`). An inline block comment may be treated as a note without punctuation. Source lines which are entirely a comment should be limited to 80 characters in length (including comment sigils, but excluding indentation) or the maximum width of the line (including comment sigils and indentation), whichever is smaller: `#![allow(unused)] fn main() { // This comment goes up to the ................................. 80 char margin. { // This comment is .............................................. 80 chars wide. } { { { { { { // This comment is limited by the ......................... 100 char margin. } } } } } } }` Prefer line comments (`///`) to block comments (`/** ... */`). Prefer outer doc comments (`///` or `/** ... */`), only use inner doc comments (`//!` and `/*! ... */`) to write module-level or crate-level documentation. Put doc comments before attributes. Put each attribute on its own line, indented to the level of the item. In the case of inner attributes (`#!`), indent it to the level of the inside of the item. Prefer outer attributes, where possible. For attributes with argument lists, format like functions. `#![allow(unused)] fn main() { #[repr(C)] #[foo(foo, bar)] #[long_multi_line_attribute( split, across, lines, )] struct CRepr { #![repr(C)] x: f32, y: f32, } }` For attributes with an equal sign, put a single space before and after the `=`, e.g., `#[foo = 42]`. There must only be a single `derive` attribute. Note for tool authors: if combining multiple `derive` attributes into a single attribute, the ordering of the derived names must generally be preserved for correctness: `#[derive(Foo)] #[derive(Bar)] struct Baz;` must be formatted to `#[derive(Foo, Bar)] struct Baz;`. In many places in this guide we specify formatting that depends on a code construct being _small_. For example, single-line vs multi-line struct literals: `#![allow(unused)] fn main() { // Normal formatting Foo { f1: an_expression, f2: another_expression(), } // "small" formatting Foo { f1, f2 } }` We leave it to individual tools to decide on exactly what _small_ means. In particular, tools are free to use different definitions in different circumstances. Some suitable heuristics are the size of the item (in characters) or the complexity of an item (for example, that all components must be simple names, not more complex sub-expressions). For more discussion on suitable heuristics, see [this issue](https://github.com/rust-lang-nursery/fmt-rfcs/issues/47) . [Non-formatting conventions](https://doc.rust-lang.org/stable/style-guide/advice.html) --------------------------------------------------------------------------------------- [Cargo.toml conventions](https://doc.rust-lang.org/stable/style-guide/cargo.html) ---------------------------------------------------------------------------------- [Principles used for deciding these guidelines](https://doc.rust-lang.org/stable/style-guide/principles.html) -------------------------------------------------------------------------------------------------------------- --- # What is rustdoc? - The rustdoc book Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The rustdoc book ================ [](https://doc.rust-lang.org/stable/rustdoc/print.html "Print this book") [](https://github.com/rust-lang/rust/tree/master/src/doc/rustdoc "Git repository") The standard Rust distribution ships with a tool called `rustdoc`. Its job is to generate documentation for Rust projects. On a fundamental level, Rustdoc takes as an argument either a crate root or a Markdown file, and produces HTML, CSS, and JavaScript. Let's give it a try! Create a new project with Cargo: `$ cargo new docs --lib $ cd docs` In `src/lib.rs`, Cargo has generated some sample code. Delete it and replace it with this: `#![allow(unused)] fn main() { /// foo is a function fn foo() {} }` Let's run `rustdoc` on our code. To do so, we can call it with the path to our crate root like this: `$ rustdoc src/lib.rs` This will create a new directory, `doc`, with a website inside! In our case, the main page is located in `doc/lib/index.html`. If you open that up in a web browser, you will see a page with a search bar, and "Crate lib" at the top, with no contents. You can also use `cargo doc` to generate documentation for the whole project. See [Using rustdoc with Cargo](https://doc.rust-lang.org/stable/rustdoc/index.html#using-rustdoc-with-cargo) . There are two problems with this: first, why does it think that our crate is named "lib"? Second, why does it not have any contents? The first problem is due to `rustdoc` trying to be helpful; like `rustc`, it assumes that our crate's name is the name of the file for the crate root. To fix this, we can pass in a command-line flag: `$ rustdoc src/lib.rs --crate-name docs` Now, `doc/docs/index.html` will be generated, and the page says "Crate docs." For the second issue, it is because our function `foo` is not public; `rustdoc` defaults to generating documentation for only public functions. If we change our code... `#![allow(unused)] fn main() { /// foo is a function pub fn foo() {} }` ... and then re-run `rustdoc`: `$ rustdoc src/lib.rs --crate-name docs` We now have some generated documentation. Open up `doc/docs/index.html` and check it out! It should show a link to the `foo` function's page, which is located at `doc/docs/fn.foo.html`. On that page, you'll see the "foo is a function" we put inside the documentation comment in our crate. Cargo also has integration with `rustdoc` to make it easier to generate docs. Instead of the `rustdoc` command, we could have done this: `$ cargo doc` If you want `cargo` to automatically open the generated documentation, you can use: `$ cargo doc --open` Internally, `cargo doc` calls out to `rustdoc` like this: `$ rustdoc --crate-name docs src/lib.rs -o /docs/target/doc -L dependency=/docs/target/debug/deps` You can see this with `cargo doc --verbose`. It generates the correct `--crate-name` for us, as well as pointing to `src/lib.rs`. But what about those other arguments? * `-o` controls the _o_utput of our docs. Instead of a top-level `doc` directory, notice that Cargo puts generated documentation under `target`. That is the idiomatic place for generated files in Cargo projects. * `-L` flag helps rustdoc find the dependencies your code relies on. If our project used dependencies, we would get documentation for them as well! The `///` syntax is used to document the item present after it. That's why it is called an outer documentation. There is another syntax: `//!`, which is used to document the item it is present inside. It is called an inner documentation. It is often used when documenting the entire crate, because nothing comes before it: it is the root of the crate. So in order to document an entire crate, you need to use `//!` syntax. For example: `#![allow(unused)] fn main() { //! This is my first rust crate }` When used in the crate root, it documents the item it is inside, which is the crate itself. For more information about the `//!` syntax, see [the Book](https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#commenting-contained-items) . `rustdoc` can also generate HTML from standalone Markdown files. Let' s give it a try: create a `README.md` file with these contents: `` # Docs This is a project to test out `rustdoc`. [Here is a link!](https://www.rust-lang.org) ## Example ```rust fn foo() -> i32 { 1 + 1 } ``` `` And call `rustdoc` on it: `$ rustdoc README.md` You will find an HTML file in `docs/doc/README.html` generated from its Markdown contents. Cargo currently does not understand standalone Markdown files, unfortunately. This covers the simplest use-cases of `rustdoc`. The rest of this book will explain all of the options that `rustdoc` has, and how to use them. --- # Introduction - Clippy Documentation Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu Clippy Documentation ==================== [](https://doc.rust-lang.org/stable/clippy/print.html "Print this book") [](https://github.com/rust-lang/rust-clippy/tree/master/book "Git repository") [](https://github.com/rust-lang/rust-clippy/edit/master/book/src/README.md "Suggest an edit") [![License: MIT OR Apache-2.0](https://img.shields.io/crates/l/clippy.svg)](https://github.com/rust-lang/rust-clippy#license) A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code. [There are over 750 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html) Lints are divided into categories, each with a default [lint level](https://doc.rust-lang.org/rustc/lints/levels.html) . You can choose how much Clippy is supposed to ~annoy~ help you by changing the lint level by category. | Category | Description | Default level | | --- | --- | --- | | `clippy::all` | all lints that are on by default (correctness, suspicious, style, complexity, perf) | **warn/deny** | | `clippy::correctness` | code that is outright wrong or useless | **deny** | | `clippy::suspicious` | code that is most likely wrong or useless | **warn** | | `clippy::style` | code that should be written in a more idiomatic way | **warn** | | `clippy::complexity` | code that does something simple but in a complex way | **warn** | | `clippy::perf` | code that can be written to run faster | **warn** | | `clippy::pedantic` | lints which are rather strict or have occasional false positives | allow | | `clippy::restriction` | lints which prevent the use of language and library features[1](https://doc.rust-lang.org/stable/clippy/index.html#footnote-restrict) | allow | | `clippy::nursery` | new lints that are still under development | allow | | `clippy::cargo` | lints for the cargo manifest | allow | More to come, please [file an issue](https://github.com/rust-lang/rust-clippy/issues) if you have ideas! The `restriction` category should, _emphatically_, not be enabled as a whole. The contained lints may lint against perfectly reasonable code, may not have an alternative suggestion, and may contradict any other lints (including other categories). Lints should be considered on a case-by-case basis before enabling. * * * 1. Some use cases for `restriction` lints include: * Strict coding styles (e.g. [`clippy::else_if_without_else`](https://rust-lang.github.io/rust-clippy/master/index.html#else_if_without_else) ). * Additional restrictions on CI (e.g. [`clippy::todo`](https://rust-lang.github.io/rust-clippy/master/index.html#todo) ). * Preventing panicking in certain functions (e.g. [`clippy::unwrap_used`](https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used) ). * Running a lint only on a subset of code (e.g. `#[forbid(clippy::float_arithmetic)]` on a module). [↩](https://doc.rust-lang.org/stable/clippy/index.html#fr-restrict-1) --- # Introduction - The Embedded Rust Book Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Embedded Rust Book ====================== [](https://doc.rust-lang.org/stable/embedded-book/print.html "Print this book") [](https://github.com/rust-embedded/book "Git repository") Welcome to The Embedded Rust Book: An introductory book about using the Rust Programming Language on "Bare Metal" embedded systems, such as Microcontrollers. Embedded Rust is for everyone who wants to do embedded programming while taking advantage of the higher-level concepts and safety guarantees the Rust language provides. (See also [Who Rust Is For](https://doc.rust-lang.org/book/ch00-00-introduction.html) ) The goals of this book are: * Get developers up to speed with embedded Rust development. i.e. How to set up a development environment. * Share _current_ best practices about using Rust for embedded development. i.e. How to best use Rust language features to write more correct embedded software. * Serve as a cookbook in some cases. e.g. How do I mix C and Rust in a single project? This book tries to be as general as possible but to make things easier for both the readers and the writers it uses the ARM Cortex-M architecture in all its examples. However, the book doesn't assume that the reader is familiar with this particular architecture and explains details particular to this architecture where required. This book caters towards people with either some embedded background or some Rust background, however we believe everybody curious about embedded Rust programming can get something out of this book. For those without any prior knowledge we suggest you read the "Assumptions and Prerequisites" section and catch up on missing knowledge to get more out of the book and improve your reading experience. You can check out the "Other Resources" section to find resources on topics you might want to catch up on. * You are comfortable using the Rust Programming Language, and have written, run, and debugged Rust applications on a desktop environment. You should also be familiar with the idioms of the [2018 edition](https://doc.rust-lang.org/edition-guide/) as this book targets Rust 2018. * You are comfortable developing and debugging embedded systems in another language such as C, C++, or Ada, and are familiar with concepts such as: * Cross Compilation * Memory Mapped Peripherals * Interrupts * Common interfaces such as I2C, SPI, Serial, etc. If you are unfamiliar with anything mentioned above or if you want more information about a specific topic mentioned in this book you might find some of these resources helpful. | Topic | Resource | Description | | --- | --- | --- | | Rust | [Rust Book](https://doc.rust-lang.org/book/) | If you are not yet comfortable with Rust, we highly suggest reading this book. | | Rust, Embedded | [Discovery Book](https://docs.rust-embedded.org/discovery/) | If you have never done any embedded programming, this book might be a better start | | Rust, Embedded | [Embedded Rust Bookshelf](https://docs.rust-embedded.org/) | Here you can find several other resources provided by Rust's Embedded Working Group. | | Rust, Embedded | [Embedonomicon](https://docs.rust-embedded.org/embedonomicon/) | The nitty gritty details when doing embedded programming in Rust. | | Rust, Embedded | [embedded FAQ](https://docs.rust-embedded.org/faq.html) | Frequently asked questions about Rust in an embedded context. | | Rust, Embedded | [Comprehensive Rust 🦀: Bare Metal](https://google.github.io/comprehensive-rust/bare-metal.html) | Teaching material for a 1-day class on bare-metal Rust development | | Interrupts | [Interrupt](https://en.wikipedia.org/wiki/Interrupt) | \- | | Memory-mapped IO/Peripherals | [Memory-mapped I/O](https://en.wikipedia.org/wiki/Memory-mapped_I/O) | \- | | SPI, UART, RS232, USB, I2C, TTL | [Stack Exchange about SPI, UART, and other interfaces](https://electronics.stackexchange.com/questions/37814/usart-uart-rs232-usb-spi-i2c-ttl-etc-what-are-all-of-these-and-how-do-th) | \- | This book has been translated by generous volunteers. If you would like your translation listed here, please open a PR to add it. * [Japanese](https://tomoyuki-nakabayashi.github.io/book/) ([repository](https://github.com/tomoyuki-nakabayashi/book) ) * [Chinese](https://xxchang.github.io/book/) ([repository](https://github.com/XxChang/book) ) This book generally assumes that you’re reading it front-to-back. Later chapters build on concepts in earlier chapters, and earlier chapters may not dig into details on a topic, revisiting the topic in a later chapter. This book will be using the [STM32F3DISCOVERY](http://www.st.com/en/evaluation-tools/stm32f3discovery.html) development board from STMicroelectronics for the majority of the examples contained within. This board is based on the ARM Cortex-M architecture, and while basic functionality is the same across most CPUs based on this architecture, peripherals and other implementation details of Microcontrollers are different between different vendors, and often even different between Microcontroller families from the same vendor. For this reason, we suggest purchasing the [STM32F3DISCOVERY](http://www.st.com/en/evaluation-tools/stm32f3discovery.html) development board for the purpose of following the examples in this book. The work on this book is coordinated in [this repository](https://github.com/rust-embedded/book) and is mainly developed by the [resources team](https://github.com/rust-embedded/wg#the-resources-team) . If you have trouble following the instructions in this book or find that some section of the book is not clear enough or hard to follow then that's a bug and it should be reported in [the issue tracker](https://github.com/rust-embedded/book/issues/) of this book. Pull requests fixing typos and adding new content are very welcome! This book is distributed under the following licenses: * The code samples and free-standing Cargo projects contained within this book are licensed under the terms of both the [MIT License](https://opensource.org/licenses/MIT) and the [Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0) . * The written prose, pictures and diagrams contained within this book are licensed under the terms of the Creative Commons [CC-BY-SA v4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode) license. TL;DR: If you want to use our text or images in your work, you need to: * Give the appropriate credit (i.e. mention this book on your slide, and provide a link to the relevant page) * Provide a link to the [CC-BY-SA v4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode) licence * Indicate if you have changed the material in any way, and make any changes to our material available under the same licence Also, please do let us know if you find this book useful! --- # Introduction - The Rustonomicon Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rustonomicon ================ [](https://doc.rust-lang.org/stable/nomicon/print.html "Print this book") [](https://github.com/rust-lang/nomicon "Git repository") Warning: This book is incomplete. Documenting everything and rewriting outdated parts take a while. See the [issue tracker](https://github.com/rust-lang/nomicon/issues) to check what's missing/outdated, and if there are any mistakes or ideas that haven't been reported, feel free to open a new issue there. > THE KNOWLEDGE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF UNLEASHING INDESCRIBABLE HORRORS THAT SHATTER YOUR PSYCHE AND SET YOUR MIND ADRIFT IN THE UNKNOWABLY INFINITE COSMOS. The Rustonomicon digs into all the awful details that you need to understand when writing Unsafe Rust programs. Should you wish a long and happy career of writing Rust programs, you should turn back now and forget you ever saw this book. It is not necessary. However if you intend to write unsafe code — or just want to dig into the guts of the language — this book contains lots of useful information. Unlike _[The Rust Programming Language](https://doc.rust-lang.org/stable/book/index.html) _, we will be assuming considerable prior knowledge. In particular, you should be comfortable with basic systems programming and Rust. If you don't feel comfortable with these topics, you should consider reading [The Book](https://doc.rust-lang.org/stable/book/index.html) first. That said, we won't assume you have read it, and we will take care to occasionally give a refresher on the basics where appropriate. You can skip straight to this book if you want; just know that we won't be explaining everything from the ground up. This book exists primarily as a high-level companion to [The Reference](https://doc.rust-lang.org/stable/reference/index.html) . Where The Reference exists to detail the syntax and semantics of every part of the language, The Rustonomicon exists to describe how to use those pieces together, and the issues that you will have in doing so. The Reference will tell you the syntax and semantics of references, destructors, and unwinding, but it won't tell you how combining them can lead to exception-safety issues, or how to deal with those issues. It should be noted that we haven't synced The Rustnomicon and The Reference well, so they may have duplicate content. In general, if the two documents disagree, The Reference should be assumed to be correct (it isn't yet considered normative, it's just better maintained). Topics that are within the scope of this book include: the meaning of (un)safety, unsafe primitives provided by the language and standard library, techniques for creating safe abstractions with those unsafe primitives, subtyping and variance, exception-safety (panic/unwind-safety), working with uninitialized memory, type punning, concurrency, interoperating with other languages (FFI), optimization tricks, how constructs lower to compiler/OS/hardware primitives, how to **not** make the memory model people angry, how you're **going** to make the memory model people angry, and more. The Rustonomicon is not a place to exhaustively describe the semantics and guarantees of every single API in the standard library, nor is it a place to exhaustively describe every feature of Rust. Unless otherwise noted, Rust code in this book uses the Rust 2024 edition. --- # Introduction - The Cargo Book Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Cargo Book ============== [](https://doc.rust-lang.org/stable/cargo/print.html "Print this book") [](https://github.com/rust-lang/cargo/tree/master/src/doc/src "Git repository") [](https://github.com/rust-lang/cargo/edit/master/src/doc/src/index.md "Suggest an edit") ![Cargo Logo](https://doc.rust-lang.org/stable/cargo/images/Cargo-Logo-Small.png) Cargo is the [Rust](https://www.rust-lang.org/) [_package manager_](https://doc.rust-lang.org/stable/cargo/appendix/glossary.html#package-manager ""package manager" (glossary entry)") . Cargo downloads your Rust [package](https://doc.rust-lang.org/stable/cargo/appendix/glossary.html#package ""package" (glossary entry)") ’s dependencies, compiles your packages, makes distributable packages, and uploads them to [crates.io](https://crates.io/) , the Rust community’s [_package registry_](https://doc.rust-lang.org/stable/cargo/appendix/glossary.html#package-registry ""package registry" (glossary entry)") . You can contribute to this book on [GitHub](https://github.com/rust-lang/cargo/tree/master/src/doc) . **[Getting Started](https://doc.rust-lang.org/stable/cargo/getting-started/index.html) ** To get started with Cargo, install Cargo (and Rust) and set up your first [_crate_](https://doc.rust-lang.org/stable/cargo/appendix/glossary.html#crate ""crate" (glossary entry)") . **[Cargo Guide](https://doc.rust-lang.org/stable/cargo/guide/index.html) ** The guide will give you all you need to know about how to use Cargo to develop Rust packages. **[Cargo Reference](https://doc.rust-lang.org/stable/cargo/reference/index.html) ** The reference covers the details of various areas of Cargo. **[Cargo Commands](https://doc.rust-lang.org/stable/cargo/commands/index.html) ** The commands will let you interact with Cargo using its command-line interface. **[Frequently Asked Questions](https://doc.rust-lang.org/stable/cargo/faq.html) ** **Appendices:** * [Glossary](https://doc.rust-lang.org/stable/cargo/appendix/glossary.html) * [Git Authentication](https://doc.rust-lang.org/stable/cargo/appendix/git-authentication.html) **Other Documentation:** * [Changelog](https://doc.rust-lang.org/stable/cargo/CHANGELOG.html) — Detailed notes about changes in Cargo in each release. * [Rust documentation website](https://doc.rust-lang.org/) — Links to official Rust documentation and tools. --- # Introduction - The Rust Reference Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Reference ================== [](https://doc.rust-lang.org/stable/reference/print.html "Print this book") [](https://github.com/rust-lang/reference/ "Git repository") [](https://github.com/rust-lang/reference/edit/master/src/introduction.md "Suggest an edit") This book is the primary reference for the Rust programming language. > Note > > For known bugs and omissions in this book, see our [GitHub issues](https://github.com/rust-lang/reference/issues) > . If you see a case where the compiler behavior and the text here do not agree, file an issue so we can think about which is correct. Rust has a new language release every six weeks. The first stable release of the language was Rust 1.0.0, followed by Rust 1.1.0 and so on. Tools (`rustc`, `cargo`, etc.) and documentation ([Standard library](https://doc.rust-lang.org/stable/std/index.html) , this book, etc.) are released with the language release. The latest release of this book, matching the latest Rust version, can always be found at [https://doc.rust-lang.org/reference/](https://doc.rust-lang.org/reference/) . Prior versions can be found by adding the Rust version before the “reference” directory. For example, the Reference for Rust 1.49.0 is located at [https://doc.rust-lang.org/1.49.0/reference/](https://doc.rust-lang.org/1.49.0/reference/) . This book does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate [book](https://doc.rust-lang.org/stable/book/index.html) is available to help acquire such background familiarity. This book also does not serve as a reference to the [standard library](https://doc.rust-lang.org/stable/std/index.html) included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you’re looking for may be there, not here. Similarly, this book does not usually document the specifics of `rustc` as a tool or of Cargo. `rustc` has its own [book](https://doc.rust-lang.org/stable/rustc/index.html) . Cargo has a [book](https://doc.rust-lang.org/stable/cargo/index.html) that contains a [reference](https://doc.rust-lang.org/stable/cargo/reference/index.html) . There are a few pages such as [linkage](https://doc.rust-lang.org/stable/reference/linkage.html) that still describe how `rustc` works. This book also only serves as a reference to what is available in stable Rust. For unstable features being worked on, see the [Unstable Book](https://doc.rust-lang.org/nightly/unstable-book/) . Rust compilers, including `rustc`, will perform optimizations. The reference does not specify what optimizations are allowed or disallowed. Instead, think of the compiled program as a black box. You can only probe by running it, feeding it input and observing its output. Everything that happens that way must conform to what the reference says. This book does not assume you are reading this book sequentially. Each chapter generally can be read standalone, but will cross-link to other chapters for facets of the language they refer to, but do not discuss. There are two main ways to read this document. The first is to answer a specific question. If you know which chapter answers that question, you can jump to that chapter in the table of contents. Otherwise, you can press `s` or click the magnifying glass on the top bar to search for keywords related to your question. For example, say you wanted to know when a temporary value created in a let statement is dropped. If you didn’t already know that the [lifetime of temporaries](https://doc.rust-lang.org/stable/reference/expressions.html#temporaries) is defined in the [expressions chapter](https://doc.rust-lang.org/stable/reference/expressions.html) , you could search “temporary let” and the first search result will take you to that section. The second is to generally improve your knowledge of a facet of the language. In that case, just browse the table of contents until you see something you want to know more about, and just start reading. If a link looks interesting, click it, and read about that section. That said, there is no wrong way to read this book. Read it however you feel helps you best. Like all technical books, this book has certain conventions in how it displays information. These conventions are documented here. * Statements that define a term contain that term in _italics_. Whenever that term is used outside of that chapter, it is usually a link to the section that has this definition. An _example term_ is an example of a term being defined. * The main text describes the latest stable edition. Differences to previous editions are separated in edition blocks: > 2018 Edition differences > > Before the 2018 edition, the behavior was this. As of the 2018 edition, the behavior is that. * Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in note blocks. > Note > > This is an example note. * Example blocks show an example that demonstrates some rule or points out some interesting aspect. Some examples may have hidden lines which can be viewed by clicking the eye icon that appears when hovering or tapping the example. > Example > > This is a code example. > > `#![allow(unused)] fn main() { println!("hello world"); }` * Warnings that show unsound behavior in the language or possibly confusing interactions of language features are in a special warning box. > Warning > > This is an example warning. * Code snippets inline in the text are inside `` tags. Longer code examples are in a syntax highlighted box that has controls for copying, executing, and showing hidden lines in the top right corner. `// This is a hidden line. fn main() { println!("This is a code example"); }` All examples are written for the latest edition unless otherwise stated. * The grammar and lexical productions are described in the [Notation](https://doc.rust-lang.org/stable/reference/notation.html) chapter. [\[example.rule.label\]](https://doc.rust-lang.org/stable/reference/index.html#r-example.rule.label "example.rule.label") * Rule identifiers appear before each language rule enclosed in square brackets. These identifiers provide a way to refer to and link to a specific rule in the language ([e.g.](https://doc.rust-lang.org/stable/reference/introduction.html#r-example.rule.label) ). The rule identifier uses periods to separate sections from most general to most specific ([destructors.scope.nesting.function-body](https://doc.rust-lang.org/stable/reference/destructors.html#r-destructors.scope.nesting.function-body) for example). On narrow screens, the rule name will collapse to display `[*]`. The rule name can be clicked to link to that rule. > Warning > > The organization of the rules is currently in flux. For the time being, these identifier names are not stable between releases, and links to these rules may fail if they are changed. We intend to stabilize these once the organization has settled so that links to the rule names will not break between releases. * Rules that have associated tests will include a `Tests` link below them (on narrow screens, the link is `[T]`). Clicking the link will pop up a list of tests, which can be clicked to view the test. For example, see [input.encoding.utf8](https://doc.rust-lang.org/stable/reference/input-format.html#r-input.encoding.utf8) . Linking rules to tests is an ongoing effort. See the [Test summary](https://doc.rust-lang.org/stable/reference/test-summary.html) chapter for an overview. We welcome contributions of all kinds. You can contribute to this book by opening an issue or sending a pull request to [the Rust Reference repository](https://github.com/rust-lang/reference/) . If this book does not answer your question, and you think its answer is in scope of it, please do not hesitate to [file an issue](https://github.com/rust-lang/reference/issues) or ask about it in the `t-lang/doc` stream on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/237824-t-lang.2Fdoc) . Knowing what people use this book for the most helps direct our attention to making those sections the best that they can be. And of course, if you see anything that is wrong or is non-normative but not specifically called out as such, please also [file an issue](https://github.com/rust-lang/reference/issues) . --- # What is rustc? - The rustc book Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The rustc book ============== [](https://doc.rust-lang.org/stable/rustc/print.html "Print this book") [](https://github.com/rust-lang/rust/tree/master/src/doc/rustc "Git repository") [](https://github.com/rust-lang/rust/edit/master/src/doc/rustc/src/what-is-rustc.md "Suggest an edit") [What is rustc?](https://doc.rust-lang.org/stable/rustc/index.html#what-is-rustc) [Basic usage](https://doc.rust-lang.org/stable/rustc/index.html#basic-usage) Welcome to "The rustc book"! `rustc` is the compiler for the Rust programming language, provided by the project itself. Compilers take your source code and produce binary code, either as a library or executable. Most Rust programmers don't invoke `rustc` directly, but instead do it through [Cargo](https://doc.rust-lang.org/stable/cargo/index.html) . It's all in service of `rustc` though! If you want to see how Cargo calls `rustc`, you can `$ cargo build --verbose` And it will print out each `rustc` invocation. This book can help you understand what each of these options does. Additionally, while most Rustaceans use Cargo, not all do: sometimes they integrate `rustc` into other build systems. This book should provide a guide to all of the options you'd need to do so. Let's say you've got a little hello world program in a file `hello.rs`: `fn main() { println!("Hello, world!"); }` To turn this source code into an executable, you can use `rustc`: `$ rustc hello.rs $ ./hello # on a *NIX $ .\hello.exe # on Windows` Note that we only ever pass `rustc` the _crate root_, not every file we wish to compile. For example, if we had a `main.rs` that looked like this: `mod foo; fn main() { foo::hello(); }` And a `foo.rs` that had this: `pub fn hello() { println!("Hello, world!"); }` To compile this, we'd run this command: `$ rustc main.rs` No need to tell `rustc` about `foo.rs`; the `mod` statements give it everything that it needs. This is different than how you would use a C compiler, where you invoke the compiler on each file, and then link everything together. In other words, the _crate_ is a translation unit, not a particular module. --- # Introduction - Rust By Example Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu Rust By Example =============== * [English](https://doc.rust-lang.org/stable/rust-by-example/index.html) * [日本語](https://doc.rust-lang.org/stable/rust-by-example/ja/index.html) * [中文](https://doc.rust-lang.org/stable/rust-by-example/zh/index.html) * [Español](https://doc.rust-lang.org/stable/rust-by-example/es/index.html) [](https://doc.rust-lang.org/stable/rust-by-example/print.html "Print this book") [](https://github.com/rust-lang/rust-by-example "Git repository") [](https://github.com/rust-lang/rust-by-example/edit/master/src/index.md "Suggest an edit") [Rust](https://www.rust-lang.org/) is a modern systems programming language focusing on safety, speed, and concurrency. It accomplishes these goals by being memory safe without using garbage collection. Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust concepts and standard libraries. To get even more out of these examples, don't forget to [install Rust locally](https://www.rust-lang.org/tools/install) and check out the [official docs](https://doc.rust-lang.org/std/) . Additionally for the curious, you can also [check out the source code for this site](https://github.com/rust-lang/rust-by-example) . Now let's begin! * [Hello World](https://doc.rust-lang.org/stable/rust-by-example/hello.html) - Start with a traditional Hello World program. * [Primitives](https://doc.rust-lang.org/stable/rust-by-example/primitives.html) - Learn about signed integers, unsigned integers and other primitives. * [Custom Types](https://doc.rust-lang.org/stable/rust-by-example/custom_types.html) - `struct` and `enum`. * [Variable Bindings](https://doc.rust-lang.org/stable/rust-by-example/variable_bindings.html) - mutable bindings, scope, shadowing. * [Types](https://doc.rust-lang.org/stable/rust-by-example/types.html) - Learn about changing and defining types. * [Conversion](https://doc.rust-lang.org/stable/rust-by-example/conversion.html) - Convert between different types, such as strings, integers, and floats. * [Expressions](https://doc.rust-lang.org/stable/rust-by-example/expression.html) - Learn about Expressions & how to use them. * [Flow of Control](https://doc.rust-lang.org/stable/rust-by-example/flow_control.html) - `if`/`else`, `for`, and others. * [Functions](https://doc.rust-lang.org/stable/rust-by-example/fn.html) - Learn about Methods, Closures and Higher Order Functions. * [Modules](https://doc.rust-lang.org/stable/rust-by-example/mod.html) - Organize code using modules * [Crates](https://doc.rust-lang.org/stable/rust-by-example/crates.html) - A crate is a compilation unit in Rust. Learn to create a library. * [Cargo](https://doc.rust-lang.org/stable/rust-by-example/cargo.html) - Go through some basic features of the official Rust package management tool. * [Attributes](https://doc.rust-lang.org/stable/rust-by-example/attribute.html) - An attribute is metadata applied to some module, crate or item. * [Generics](https://doc.rust-lang.org/stable/rust-by-example/generics.html) - Learn about writing a function or data type which can work for multiple types of arguments. * [Scoping rules](https://doc.rust-lang.org/stable/rust-by-example/scope.html) - Scopes play an important part in ownership, borrowing, and lifetimes. * [Traits](https://doc.rust-lang.org/stable/rust-by-example/trait.html) - A trait is a collection of methods defined for an unknown type: `Self` * [Macros](https://doc.rust-lang.org/stable/rust-by-example/macros.html) - Macros are a way of writing code that writes other code, which is known as metaprogramming. * [Error handling](https://doc.rust-lang.org/stable/rust-by-example/error.html) - Learn Rust way of handling failures. * [Std library types](https://doc.rust-lang.org/stable/rust-by-example/std.html) - Learn about some custom types provided by `std` library. * [Std misc](https://doc.rust-lang.org/stable/rust-by-example/std_misc.html) - More custom types for file handling, threads. * [Testing](https://doc.rust-lang.org/stable/rust-by-example/testing.html) - All sorts of testing in Rust. * [Unsafe Operations](https://doc.rust-lang.org/stable/rust-by-example/unsafe.html) - Learn about entering a block of unsafe operations. * [Compatibility](https://doc.rust-lang.org/stable/rust-by-example/compatibility.html) - Handling Rust's evolution and potential compatibility issues. * [Meta](https://doc.rust-lang.org/stable/rust-by-example/meta.html) - Documentation, Benchmarking. --- # Rust Release Notes ![Rust logo](https://www.rust-lang.org/logos/rust-logo-32x32-blk.png) [Rust](https://www.rust-lang.org/) 1.92.0 [ded5c06cf](https://github.com/rust-lang/rust/commit/ded5c06cf21d2b93bffd5d884aa6e96934ee4234) Rust Release Notes ================== [§](https://doc.rust-lang.org/stable/releases.html#version-1920-2025-12-11) Version 1.92.0 (2025-12-11) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language) Language --------------------------------------------------------------------- * [Document `MaybeUninit` representation and validity](https://github.com/rust-lang/rust/pull/140463) * [Allow `&raw [mut | const]` for union field in safe code](https://github.com/rust-lang/rust/pull/141469) * [Prefer item bounds of associated types over where-bounds for auto-traits and `Sized`](https://github.com/rust-lang/rust/pull/144064) * [Do not materialize `X` in `[X; 0]` when `X` is unsizing a const](https://github.com/rust-lang/rust/pull/145277) * [Support combining `#[track_caller]` and `#[no_mangle]` (requires every declaration specifying `#[track_caller]` as well)](https://github.com/rust-lang/rust/pull/145724) * [Make never type lints `never_type_fallback_flowing_into_unsafe` and `dependency_on_unit_never_type_fallback` deny-by-default](https://github.com/rust-lang/rust/pull/146167) * [Allow specifying multiple bounds for same associated item, except in trait objects](https://github.com/rust-lang/rust/pull/146593) * [Slightly strengthen higher-ranked region handling in coherence](https://github.com/rust-lang/rust/pull/146725) * [The `unused_must_use` lint no longer warns on `Result<(), Uninhabited>` (for instance, `Result<(), !>`), or `ControlFlow`](https://github.com/rust-lang/rust/pull/147382) . This avoids having to check for an error that can never happen. [§](https://doc.rust-lang.org/stable/releases.html#compiler) Compiler --------------------------------------------------------------------- * [Make `mips64el-unknown-linux-muslabi64` link dynamically](https://github.com/rust-lang/rust/pull/146858) * [Remove current code for embedding command-line args in PDB](https://github.com/rust-lang/rust/pull/147022) Command-line information is typically not needed by debugging tools, and the removed code was causing problems for incremental builds even on targets that don’t use PDB debuginfo. [§](https://doc.rust-lang.org/stable/releases.html#libraries) Libraries ----------------------------------------------------------------------- * [Specialize `Iterator::eq{_by}` for `TrustedLen` iterators](https://github.com/rust-lang/rust/pull/137122) * [Simplify `Extend` for tuples](https://github.com/rust-lang/rust/pull/138799) * [Added details to `Debug` for `EncodeWide`](https://github.com/rust-lang/rust/pull/140153) . * [`iter::Repeat::last`](https://github.com/rust-lang/rust/pull/147258) and [`count`](https://github.com/rust-lang/rust/pull/146410) will now panic, rather than looping infinitely. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis) Stabilized APIs ----------------------------------------------------------------------------------- * [`NonZero::div_ceil`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.div_ceil) * [`Location::file_as_c_str`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.file_as_c_str) * [`RwLockWriteGuard::downgrade`](https://doc.rust-lang.org/stable/std/sync/struct.RwLockWriteGuard.html#method.downgrade) * [`Box::new_zeroed`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.new_zeroed) * [`Box::new_zeroed_slice`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.new_zeroed_slice) * [`Rc::new_zeroed`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.new_zeroed) * [`Rc::new_zeroed_slice`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.new_zeroed_slice) * [`Arc::new_zeroed`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.new_zeroed) * [`Arc::new_zeroed_slice`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.new_zeroed_slice) * [`btree_map::Entry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry.html#method.insert_entry) * [`btree_map::VacantEntry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.VacantEntry.html#method.insert_entry) * [`impl Extend for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CGroup%3E-for-TokenStream) * [`impl Extend for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CLiteral%3E-for-TokenStream) * [`impl Extend for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CPunct%3E-for-TokenStream) * [`impl Extend for proc_macro::TokenStream`](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html#impl-Extend%3CIdent%3E-for-TokenStream) These previously stable APIs are now stable in const contexts: * [`<[_]>::rotate_left`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rotate_left) * [`<[_]>::rotate_right`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rotate_right) [§](https://doc.rust-lang.org/stable/releases.html#cargo) Cargo --------------------------------------------------------------- * [Added a new chapter](https://github.com/rust-lang/cargo/issues/16119) to the Cargo book, [“Optimizing Build Performance”](https://doc.rust-lang.org/stable/cargo/guide/build-performance.html) . [§](https://doc.rust-lang.org/stable/releases.html#rustdoc) Rustdoc ------------------------------------------------------------------- * [If a trait item appears in rustdoc search, hide the corresponding impl items](https://github.com/rust-lang/rust/pull/145898) . Previously a search for “last” would show both `Iterator::last` as well as impl methods like `std::vec::IntoIter::last`. Now these impl methods will be hidden, freeing up space for inherent methods like `BTreeSet::last`. * [Relax rules for identifiers in search](https://github.com/rust-lang/rust/pull/147860) . Previously you could only search for identifiers that were valid in rust code, now searches only need to be valid as part of an identifier. For example, you can now perform a search that starts with a digit. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes) Compatibility Notes ------------------------------------------------------------------------------------------- * [Fix backtraces with `-C panic=abort` on Linux by generating unwind tables by default](https://github.com/rust-lang/rust/pull/143613) . Build with `-C force-unwind-tables=no` to keep omitting unwind tables. * As part of the larger effort refactoring compiler built-in attributes and their diagnostics, [the future-compatibility lint `invalid_macro_export_arguments` is upgraded to deny-by-default and will be reported in dependencies too.](https://github.com/rust-lang/rust/pull/143857) * [Update the minimum external LLVM to 20](https://github.com/rust-lang/rust/pull/145071) * [Prevent downstream `impl DerefMut for Pin`](https://github.com/rust-lang/rust/pull/145608) * [Don’t apply temporary lifetime extension rules to the arguments of non-extended `pin!` and formatting macros](https://github.com/rust-lang/rust/pull/145838) [§](https://doc.rust-lang.org/stable/releases.html#version-1911-2025-11-10) Version 1.91.1 (2025-11-10) ======================================================================================================= * [Enable file locking support in illumos](https://github.com/rust-lang/rust/pull/148322) . This fixes Cargo not locking the build directory on illumos. * [Fix `wasm_import_module` attribute cross-crate](https://github.com/rust-lang/rust/pull/148363) . This fixes linker errors on WASM targets. [§](https://doc.rust-lang.org/stable/releases.html#version-1910-2025-10-30) Version 1.91.0 (2025-10-30) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-1) Language ----------------------------------------------------------------------- * [Lower pattern bindings in the order they’re written and base drop order on primary bindings’ order](https://github.com/rust-lang/rust/pull/143764) * [Stabilize declaration of C-style variadic functions for `sysv64`, `win64`, `efiapi`, and `aapcs` ABIs](https://github.com/rust-lang/rust/pull/144066) . This brings these ABIs in line with the C ABI: variadic functions can be declared in extern blocks but not defined. * [Add `dangling_pointers_from_locals` lint to warn against dangling pointers from local variables](https://github.com/rust-lang/rust/pull/144322) * [Upgrade `semicolon_in_expressions_from_macros` from warn to deny](https://github.com/rust-lang/rust/pull/144369) * [Stabilize LoongArch32 inline assembly](https://github.com/rust-lang/rust/pull/144402) * [Add warn-by-default `integer_to_ptr_transmutes` lint against integer-to-pointer transmutes](https://github.com/rust-lang/rust/pull/144531) * [Stabilize `sse4a` and `tbm` target features](https://github.com/rust-lang/rust/pull/144542) * [Add `target_env = "macabi"` and `target_env = "sim"` cfgs](https://github.com/rust-lang/rust/pull/139451) as replacements for the `target_abi` cfgs with the same values. [§](https://doc.rust-lang.org/stable/releases.html#compiler-1) Compiler ----------------------------------------------------------------------- * [Don’t warn on never-to-any `as` casts as unreachable](https://github.com/rust-lang/rust/pull/144804) [§](https://doc.rust-lang.org/stable/releases.html#platform-support) Platform Support ------------------------------------------------------------------------------------- * [Promote `aarch64-pc-windows-gnullvm` and `x86_64-pc-windows-gnullvm` to Tier 2 with host tools.](https://github.com/rust-lang/rust/pull/143031) Note: llvm-tools and MSI installers are missing but will be added in future releases. * [Promote `aarch64-pc-windows-msvc` to Tier 1](https://github.com/rust-lang/rust/pull/145682) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-1) Libraries ------------------------------------------------------------------------- * [Print thread ID in panic message](https://github.com/rust-lang/rust/pull/115746) * [Fix overly restrictive lifetime in `core::panic::Location::file` return type](https://github.com/rust-lang/rust/pull/132087) * [Guarantee parameter order for `_by()` variants of `min` / `max`/ `minmax` in `std::cmp`](https://github.com/rust-lang/rust/pull/139357) * [Document assumptions about `Clone` and `Eq` traits](https://github.com/rust-lang/rust/pull/144330/) * [`std::thread`: Return error if setting thread stack size fails](https://github.com/rust-lang/rust/pull/144210) This used to panic within the standard library. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-1) Stabilized APIs ------------------------------------------------------------------------------------- * [`Path::file_prefix`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.file_prefix) * [`AtomicPtr::fetch_ptr_add`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_ptr_add) * [`AtomicPtr::fetch_ptr_sub`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_ptr_sub) * [`AtomicPtr::fetch_byte_add`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_byte_add) * [`AtomicPtr::fetch_byte_sub`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_byte_sub) * [`AtomicPtr::fetch_or`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_or) * [`AtomicPtr::fetch_and`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_and) * [`AtomicPtr::fetch_xor`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.fetch_xor) * [`{integer}::strict_add`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_add) * [`{integer}::strict_sub`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_sub) * [`{integer}::strict_mul`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_mul) * [`{integer}::strict_div`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_div) * [`{integer}::strict_div_euclid`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_div_euclid) * [`{integer}::strict_rem`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_rem) * [`{integer}::strict_rem_euclid`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_rem_euclid) * [`{integer}::strict_neg`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_neg) * [`{integer}::strict_shl`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_shl) * [`{integer}::strict_shr`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_shr) * [`{integer}::strict_pow`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_pow) * [`i{N}::strict_add_unsigned`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_add_unsigned) * [`i{N}::strict_sub_unsigned`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_sub_unsigned) * [`i{N}::strict_abs`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.strict_abs) * [`u{N}::strict_add_signed`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_add_signed) * [`u{N}::strict_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.strict_sub_signed) * [`PanicHookInfo::payload_as_str`](https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html#method.payload_as_str) * [`core::iter::chain`](https://doc.rust-lang.org/stable/core/iter/fn.chain.html) * [`u{N}::checked_signed_diff`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.checked_signed_diff) * [`core::array::repeat`](https://doc.rust-lang.org/stable/core/array/fn.repeat.html) * [`PathBuf::add_extension`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.add_extension) * [`PathBuf::with_added_extension`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.with_added_extension) * [`Duration::from_mins`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_mins) * [`Duration::from_hours`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_hours) * [`impl PartialEq for PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#impl-PartialEq%3Cstr%3E-for-PathBuf) * [`impl PartialEq for PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#impl-PartialEq%3CString%3E-for-PathBuf) * [`impl PartialEq for Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#impl-PartialEq%3Cstr%3E-for-Path) * [`impl PartialEq for Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#impl-PartialEq%3CString%3E-for-Path) * [`impl PartialEq for String`](https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-PartialEq%3CPathBuf%3E-for-String) * [`impl PartialEq for String`](https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-PartialEq%3CPath%3E-for-String) * [`impl PartialEq for str`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-PartialEq%3CPathBuf%3E-for-str) * [`impl PartialEq for str`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-PartialEq%3CPath%3E-for-str) * [`Ipv4Addr::from_octets`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.from_octets) * [`Ipv6Addr::from_octets`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.from_octets) * [`Ipv6Addr::from_segments`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.from_segments) * [`impl Default for Pin> where Box: Default, T: ?Sized`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#impl-Default-for-Pin%3CBox%3CT%3E%3E) * [`impl Default for Pin> where Rc: Default, T: ?Sized`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#impl-Default-for-Pin%3CRc%3CT%3E%3E) * [`impl Default for Pin> where Arc: Default, T: ?Sized`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#impl-Default-for-Pin%3CArc%3CT%3E%3E) * [`Cell::as_array_of_cells`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.as_array_of_cells) * [`u{N}::carrying_add`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.carrying_add) * [`u{N}::borrowing_sub`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.borrowing_sub) * [`u{N}::carrying_mul`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.carrying_mul) * [`u{N}::carrying_mul_add`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.carrying_mul_add) * [`BTreeMap::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html#method.extract_if) * [`BTreeSet::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html#method.extract_if) * [`impl Debug for windows::ffi::EncodeWide<'_>`](https://doc.rust-lang.org/stable/std/os/windows/ffi/struct.EncodeWide.html#impl-Debug-for-EncodeWide%3C'_%3E) * [`str::ceil_char_boundary`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.ceil_char_boundary) * [`str::floor_char_boundary`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.floor_char_boundary) * [`impl Sum for Saturating`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Sum-for-Saturating%3Cu32%3E) * [`impl Sum<&Self> for Saturating`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Sum%3C%26Saturating%3Cu32%3E%3E-for-Saturating%3Cu32%3E) * [`impl Product for Saturating`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Product-for-Saturating%3Cu32%3E) * [`impl Product<&Self> for Saturating`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html#impl-Product%3C%26Saturating%3Cu32%3E%3E-for-Saturating%3Cu32%3E) These previously stable APIs are now stable in const contexts: * [`<[T; N]>::each_ref`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_ref) * [`<[T; N]>::each_mut`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_mut) * [`OsString::new`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.new) * [`PathBuf::new`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.new) * [`TypeId::of`](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.of) * [`ptr::with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html) * [`ptr::with_exposed_provenance_mut`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance_mut.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-1) Cargo ----------------------------------------------------------------- * 🎉 Stabilize `build.build-dir`. This config sets the directory where intermediate build artifacts are stored. These artifacts are produced by Cargo and rustc during the build process. End users usually won’t need to interact with them, and the layout inside `build-dir` is an implementation detail that may change without notice. ([config doc](https://doc.rust-lang.org/stable/cargo/reference/config.html#buildbuild-dir) ) ([build cache doc](https://doc.rust-lang.org/stable/cargo/reference/build-cache.html) ) [#15833](https://github.com/rust-lang/cargo/pull/15833) [#15840](https://github.com/rust-lang/cargo/pull/15840) * The `--target` flag and the `build.target` configuration can now take literal `"host-tuple"` string, which will internally be substituted by the host machine’s target triple. [#15838](https://github.com/rust-lang/cargo/pull/15838) [#16003](https://github.com/rust-lang/cargo/pull/16003) [#16032](https://github.com/rust-lang/cargo/pull/16032) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-1) Rustdoc --------------------------------------------------------------------- * [In search results, rank doc aliases lower than non-alias items with the same name](https://github.com/rust-lang/rust/pull/145100) * [Raw pointers now work in type-based search like references](https://github.com/rust-lang/rust/pull/145731) . This means you can now search for things like `*const u8 ->`, and additionally functions that take or return raw pointers will now display their signature properly in search results. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-1) Compatibility Notes --------------------------------------------------------------------------------------------- * [Always require coroutine captures to be drop-live](https://github.com/rust-lang/rust/pull/144156) * [Apple: Always pass SDK root when linking with `cc`, and pass it via `SDKROOT` env var](https://github.com/rust-lang/rust/pull/131477) . This should fix linking issues with `rustc` running inside Xcode. Libraries in `/usr/local/lib` may no longer be linked automatically, if you develop or use a crate that relies on this, you should explicitly set `cargo::rustc-link-search=/usr/local/lib` in a `build.rs` script. * [Relaxed bounds in associated type bound position like in `TraitRef` are now correctly forbidden](https://github.com/rust-lang/rust/pull/135331) * [Add unstable `#[sanitize(xyz = "on|off")]` built-in attribute that shadows procedural macros with the same name](https://github.com/rust-lang/rust/pull/142681) * [Fix the drop checker being more permissive for bindings declared with let-else](https://github.com/rust-lang/rust/pull/143028) * [Be more strict when parsing attributes, erroring on many invalid attributes](https://github.com/rust-lang/rust/pull/144689) * [Error on invalid `#[should_panic]` attributes](https://github.com/rust-lang/rust/pull/143808) * [Error on invalid `#[link]` attributes](https://github.com/rust-lang/rust/pull/143193) * [Mark all deprecation lints in name resolution as deny-by-default and also report in dependencies](https://github.com/rust-lang/rust/pull/143929) * The lint `semicolon_in_expressions_from_macros`, for `macro_rules!` macros in expression position that expand to end in a semicolon (`;`), is now deny-by-default. It was already warn-by-default, and a future compatibility warning (FCW) that warned even in dependencies. This lint will become a hard error in the future. * [Trait impl modifiers (e.g., `unsafe`, `!`, `default`) in inherent impls are no longer syntactically valid](https://github.com/rust-lang/rust/pull/144386) * [Start reporting future breakage for `ill_formed_attribute_input` in dependencies](https://github.com/rust-lang/rust/pull/144544) * [Restrict the scope of temporaries created by the macros `pin!`, `format_args!`, `write!`, and `writeln!` in `if let` scrutinees in Rust Edition 2024.](https://github.com/rust-lang/rust/pull/145342) This applies [Rust Edition 2024’s `if let` temporary scope rules](https://doc.rust-lang.org/edition-guide/rust-2024/temporary-if-let-scope.html) to these temporaries, which previously could live past the `if` expression regardless of Edition. * [Invalid numeric literal suffixes in tuple indexing, tuple struct indexing, and struct field name positions are now correctly rejected](https://github.com/rust-lang/rust/pull/145463) * [Closures marked with the keyword `static` are now syntactically invalid](https://github.com/rust-lang/rust/pull/145604) * [Shebangs inside `--cfg` and `--check-cfg` arguments are no longer allowed](https://github.com/rust-lang/rust/pull/146211) * [Add future incompatibility lint for temporary lifetime shortening in Rust 1.92](https://github.com/rust-lang/rust/pull/147056) Cargo compatibility notes: * `cargo publish` no longer keeps `.crate` tarballs as final build artifacts when `build.build-dir` is set. These tarballs were previously included due to an oversight and are now treated as intermediate artifacts. To get `.crate` tarballs as final artifacts, use `cargo package`. In a future version, this change will apply regardless of `build.build-dir`. [#15910](https://github.com/rust-lang/cargo/pull/15910) * Adjust Cargo messages to match rustc diagnostic style. This changes some of the terminal colors used by Cargo messages. [#15928](https://github.com/rust-lang/cargo/pull/15928) * Tools and projects relying on the [internal details of Cargo’s `build-dir`](https://doc.rust-lang.org/cargo/reference/build-cache.html) may not work for users changing their `build-dir` layout. For those doing so, we’d recommend proactively testing these cases particularly as we are considering changing the default location of the `build-dir` in the future ([cargo#16147](https://github.com/rust-lang/cargo/issues/16147) ). If you can’t migrate off of Cargo’s internal details, we’d like to learn more about your use case as we prepare to change the layout of the `build-dir` ([cargo#15010](https://github.com/rust-lang/cargo/issues/15010) ). [§](https://doc.rust-lang.org/stable/releases.html#internal-changes) Internal Changes ------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Update to LLVM 21](https://github.com/rust-lang/rust/pull/143684) [§](https://doc.rust-lang.org/stable/releases.html#version-1900-2025-09-18) Version 1.90.0 (2025-09-18) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-2) Language ----------------------------------------------------------------------- * [Split up the `unknown_or_malformed_diagnostic_attributes` lint](https://github.com/rust-lang/rust/pull/140717) . This lint has been split up into four finer-grained lints, with `unknown_or_malformed_diagnostic_attributes` now being the lint group that contains these lints: 1. `unknown_diagnostic_attributes`: unknown to the current compiler 2. `misplaced_diagnostic_attributes`: placed on the wrong item 3. `malformed_diagnostic_attributes`: malformed attribute syntax or options 4. `malformed_diagnostic_format_literals`: malformed format string literal * [Allow constants whose final value has references to mutable/external memory, but reject such constants as patterns](https://github.com/rust-lang/rust/pull/140942) * [Allow volatile access to non-Rust memory, including address 0](https://github.com/rust-lang/rust/pull/141260) [§](https://doc.rust-lang.org/stable/releases.html#compiler-2) Compiler ----------------------------------------------------------------------- * [Use `lld` by default on `x86_64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/140525) . * [Tier 3 `musl` targets now link dynamically by default](https://github.com/rust-lang/rust/pull/144410) . Affected targets: * `mips64-unknown-linux-muslabi64` * `powerpc64-unknown-linux-musl` * `powerpc-unknown-linux-musl` * `powerpc-unknown-linux-muslspe` * `riscv32gc-unknown-linux-musl` * `s390x-unknown-linux-musl` * `thumbv7neon-unknown-linux-musleabihf` [§](https://doc.rust-lang.org/stable/releases.html#platform-support-1) Platform Support --------------------------------------------------------------------------------------- * [Demote `x86_64-apple-darwin` to Tier 2 with host tools](https://github.com/rust-lang/rust/pull/145252) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-2) Libraries ------------------------------------------------------------------------- * [Stabilize `u*::{checked,overflowing,saturating,wrapping}_sub_signed`](https://github.com/rust-lang/rust/issues/126043) * [Allow comparisons between `CStr`, `CString`, and `Cow`](https://github.com/rust-lang/rust/pull/137268) * [Remove some unsized tuple impls since unsized tuples can’t be constructed](https://github.com/rust-lang/rust/pull/138340) * [Set `MSG_NOSIGNAL` for `UnixStream`](https://github.com/rust-lang/rust/pull/140005) * [`proc_macro::Ident::new` now supports `$crate`.](https://github.com/rust-lang/rust/pull/141996) * [Guarantee the pointer returned from `Thread::into_raw` has at least 8 bytes of alignment](https://github.com/rust-lang/rust/pull/143859) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-2) Stabilized APIs ------------------------------------------------------------------------------------- * [`u{n}::checked_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.checked_sub_signed) * [`u{n}::overflowing_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.overflowing_sub_signed) * [`u{n}::saturating_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.saturating_sub_signed) * [`u{n}::wrapping_sub_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.wrapping_sub_signed) * [`impl Copy for IntErrorKind`](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Copy-for-IntErrorKind) * [`impl Hash for IntErrorKind`](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Hash-for-IntErrorKind) * [`impl PartialEq<&CStr> for CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#impl-PartialEq%3C%26CStr%3E-for-CStr) * [`impl PartialEq for CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#impl-PartialEq%3CCString%3E-for-CStr) * [`impl PartialEq> for CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#impl-PartialEq%3CCow%3C'_,+CStr%3E%3E-for-CStr) * [`impl PartialEq<&CStr> for CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html#impl-PartialEq%3C%26CStr%3E-for-CString) * [`impl PartialEq for CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html#impl-PartialEq%3CCStr%3E-for-CString) * [`impl PartialEq> for CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html#impl-PartialEq%3CCow%3C'_,+CStr%3E%3E-for-CString) * [`impl PartialEq<&CStr> for Cow`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html#impl-PartialEq%3C%26CStr%3E-for-Cow%3C'_,+CStr%3E) * [`impl PartialEq for Cow`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html#impl-PartialEq%3CCStr%3E-for-Cow%3C'_,+CStr%3E) * [`impl PartialEq for Cow`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html#impl-PartialEq%3CCString%3E-for-Cow%3C'_,+CStr%3E) These previously stable APIs are now stable in const contexts: * [`<[T]>::reverse`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.reverse) * [`f32::floor`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.floor) * [`f32::ceil`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.ceil) * [`f32::trunc`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.trunc) * [`f32::fract`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.fract) * [`f32::round`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.round) * [`f32::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.round_ties_even) * [`f64::floor`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.floor) * [`f64::ceil`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.ceil) * [`f64::trunc`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.trunc) * [`f64::fract`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.fract) * [`f64::round`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.round) * [`f64::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.round_ties_even) [§](https://doc.rust-lang.org/stable/releases.html#cargo-2) Cargo ----------------------------------------------------------------- * [Add `http.proxy-cainfo` config for proxy certs](https://github.com/rust-lang/cargo/pull/15374/) * [Use `gix` for `cargo package`](https://github.com/rust-lang/cargo/pull/15534/) * [feat(publish): Stabilize multi-package publishing](https://github.com/rust-lang/cargo/pull/15636/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-2) Rustdoc --------------------------------------------------------------------- * [Add ways to collapse all impl blocks](https://github.com/rust-lang/rust/pull/141663) . Previously the “Summary” button and “-” keyboard shortcut would never collapse `impl` blocks, now they do when shift is held * [Display unsafe attributes with `unsafe()` wrappers](https://github.com/rust-lang/rust/pull/143662) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-2) Compatibility Notes --------------------------------------------------------------------------------------------- * [Use `lld` by default on `x86_64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/140525) . See also [https://blog.rust-lang.org/2025/09/01/rust-lld-on-1.90.0-stable/](https://blog.rust-lang.org/2025/09/01/rust-lld-on-1.90.0-stable/) . * [Make `core::iter::Fuse`’s `Default` impl construct `I::default()` internally as promised in the docs instead of always being empty](https://github.com/rust-lang/rust/pull/140985) * [Set `MSG_NOSIGNAL` for `UnixStream`](https://github.com/rust-lang/rust/pull/140005) This may change program behavior but results in the same behavior as other primitives (e.g., stdout, network sockets). Programs relying on signals to terminate them should update handling of sockets to handle errors on write by exiting. * [On Unix `std::env::home_dir` will use the fallback if the `HOME` environment variable is empty](https://github.com/rust-lang/rust/pull/141840) * We now [reject unsupported `extern "{abi}"`s consistently in all positions](https://github.com/rust-lang/rust/pull/142134) . This primarily affects the use of implementing traits on an `extern "{abi}"` function pointer, like `extern "stdcall" fn()`, on a platform that doesn’t support that, like aarch64-unknown-linux-gnu. Direct usage of these unsupported ABI strings by declaring or defining functions was already rejected, so this is only a change for consistency. * [const-eval: error when initializing a static writes to that static](https://github.com/rust-lang/rust/pull/143084) * [Check that the `proc_macro_derive` macro has correct arguments when applied to the crate root](https://github.com/rust-lang/rust/pull/143607) [§](https://doc.rust-lang.org/stable/releases.html#version-1890-2025-08-07) Version 1.89.0 (2025-08-07) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-3) Language ----------------------------------------------------------------------- * [Stabilize explicitly inferred const arguments (`feature(generic_arg_infer)`)](https://github.com/rust-lang/rust/pull/141610) * [Add a warn-by-default `mismatched_lifetime_syntaxes` lint.](https://github.com/rust-lang/rust/pull/138677) This lint detects when the same lifetime is referred to by different syntax categories between function arguments and return values, which can be confusing to read, especially in unsafe code. This lint supersedes the warn-by-default `elided_named_lifetimes` lint. * [Expand `unpredictable_function_pointer_comparisons` to also lint on function pointer comparisons in external macros](https://github.com/rust-lang/rust/pull/134536) * [Make the `dangerous_implicit_autorefs` lint deny-by-default](https://github.com/rust-lang/rust/pull/141661) * [Stabilize the avx512 target features](https://github.com/rust-lang/rust/pull/138940) * [Stabilize `kl` and `widekl` target features for x86](https://github.com/rust-lang/rust/pull/140766) * [Stabilize `sha512`, `sm3` and `sm4` target features for x86](https://github.com/rust-lang/rust/pull/140767) * [Stabilize LoongArch target features `f`, `d`, `frecipe`, `lasx`, `lbt`, `lsx`, and `lvz`](https://github.com/rust-lang/rust/pull/135015) * [Remove `i128` and `u128` from `improper_ctypes_definitions`](https://github.com/rust-lang/rust/pull/137306) * [Stabilize `repr128` (`#[repr(u128)]`, `#[repr(i128)]`)](https://github.com/rust-lang/rust/pull/138285) * [Allow `#![doc(test(attr(..)))]` everywhere](https://github.com/rust-lang/rust/pull/140560) * [Extend temporary lifetime extension to also go through tuple struct and tuple variant constructors](https://github.com/rust-lang/rust/pull/140593) * [`extern "C"` functions on the `wasm32-unknown-unknown` target now have a standards compliant ABI](https://blog.rust-lang.org/2025/04/04/c-abi-changes-for-wasm32-unknown-unknown/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-3) Compiler ----------------------------------------------------------------------- * [Default to non-leaf frame pointers on aarch64-linux](https://github.com/rust-lang/rust/pull/140832) * [Enable non-leaf frame pointers for Arm64EC Windows](https://github.com/rust-lang/rust/pull/140862) * [Set Apple frame pointers by architecture](https://github.com/rust-lang/rust/pull/141797) [§](https://doc.rust-lang.org/stable/releases.html#platform-support-2) Platform Support --------------------------------------------------------------------------------------- * [Add new Tier-3 targets `loongarch32-unknown-none` and `loongarch32-unknown-none-softfloat`](https://github.com/rust-lang/rust/pull/142053) * [`x86_64-apple-darwin` is in the process of being demoted to Tier 2 with host tools](https://github.com/rust-lang/rfcs/pull/3841) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-3) Libraries ------------------------------------------------------------------------- * [Specify the base path for `file!`](https://github.com/rust-lang/rust/pull/134442) * [Allow storing `format_args!()` in a variable](https://github.com/rust-lang/rust/pull/140748) * [Add `#[must_use]` to `[T; N]::map`](https://github.com/rust-lang/rust/pull/140957) * [Implement `DerefMut` for `Lazy{Cell,Lock}`](https://github.com/rust-lang/rust/pull/129334) * [Implement `Default` for `array::IntoIter`](https://github.com/rust-lang/rust/pull/141574) * [Implement `Clone` for `slice::ChunkBy`](https://github.com/rust-lang/rust/pull/138016) * [Implement `io::Seek` for `io::Take`](https://github.com/rust-lang/rust/pull/138023) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-3) Stabilized APIs ------------------------------------------------------------------------------------- * [`NonZero`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html) * Many intrinsics for x86, not enumerated here * [AVX512 intrinsics](https://github.com/rust-lang/rust/issues/111137) * [`SHA512`, `SM3` and `SM4` intrinsics](https://github.com/rust-lang/rust/issues/126624) * [`File::lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.lock) * [`File::lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.lock_shared) * [`File::try_lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock) * [`File::try_lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock_shared) * [`File::unlock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.unlock) * [`NonNull::from_ref`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.from_ref) * [`NonNull::from_mut`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.from_mut) * [`NonNull::without_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.without_provenance) * [`NonNull::with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.with_exposed_provenance) * [`NonNull::expose_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.expose_provenance) * [`OsString::leak`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.leak) * [`PathBuf::leak`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.leak) * [`Result::flatten`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.flatten) * [`std::os::linux::net::TcpStreamExt::quickack`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.TcpStreamExt.html#tymethod.quickack) * [`std::os::linux::net::TcpStreamExt::set_quickack`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.TcpStreamExt.html#tymethod.set_quickack) These previously stable APIs are now stable in const contexts: * [`<[T; N]>::as_mut_slice`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.as_mut_slice) * [`<[u8]>::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.slice.html#impl-%5Bu8%5D/method.eq_ignore_ascii_case) * [`str::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-str/method.eq_ignore_ascii_case) [§](https://doc.rust-lang.org/stable/releases.html#cargo-3) Cargo ----------------------------------------------------------------- * [`cargo fix` and `cargo clippy --fix` now default to the same Cargo target selection as other build commands.](https://github.com/rust-lang/cargo/pull/15192/) Previously it would apply to all targets (like binaries, examples, tests, etc.). The `--edition` flag still applies to all targets. * [Stabilize doctest-xcompile.](https://github.com/rust-lang/cargo/pull/15462/) Doctests are now tested when cross-compiling. Just like other tests, it will use the [`runner` setting](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerunner) to run the tests. If you need to disable tests for a target, you can use the [ignore doctest attribute](https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#ignoring-targets) to specify the targets to ignore. [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-3) Rustdoc --------------------------------------------------------------------- * [On mobile, make the sidebar full width and linewrap](https://github.com/rust-lang/rust/pull/139831) . This makes long section and item names much easier to deal with on mobile. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-3) Compatibility Notes --------------------------------------------------------------------------------------------- * [Make `missing_fragment_specifier` an unconditional error](https://github.com/rust-lang/rust/pull/128425) * [Enabling the `neon` target feature on `aarch64-unknown-none-softfloat` causes a warning](https://github.com/rust-lang/rust/pull/135160) because mixing code with and without that target feature is not properly supported by LLVM * [Sized Hierarchy: Part I](https://github.com/rust-lang/rust/pull/137944) * Introduces a small breaking change affecting `?Sized` bounds on impls on recursive types which contain associated type projections. It is not expected to affect any existing published crates. Can be fixed by refactoring the involved types or opting into the `sized_hierarchy` unstable feature. See the [FCP report](https://github.com/rust-lang/rust/pull/137944#issuecomment-2912207485) for a code example. * The warn-by-default `elided_named_lifetimes` lint is [superseded by the warn-by-default `mismatched_lifetime_syntaxes` lint.](https://github.com/rust-lang/rust/pull/138677) * [Error on recursive opaque types earlier in the type checker](https://github.com/rust-lang/rust/pull/139419) * [Type inference side effects from requiring element types of array repeat expressions are `Copy` are now only available at the end of type checking](https://github.com/rust-lang/rust/pull/139635) * [The deprecated accidentally-stable `std::intrinsics::{copy,copy_nonoverlapping,write_bytes}` are now proper intrinsics](https://github.com/rust-lang/rust/pull/139916) . There are no debug assertions guarding against UB, and they cannot be coerced to function pointers. * [Remove long-deprecated `std::intrinsics::drop_in_place`](https://github.com/rust-lang/rust/pull/140151) * [Make well-formedness predicates no longer coinductive](https://github.com/rust-lang/rust/pull/140208) * [Remove hack when checking impl method compatibility](https://github.com/rust-lang/rust/pull/140557) * [Remove unnecessary type inference due to built-in trait object impls](https://github.com/rust-lang/rust/pull/141352) * [Lint against “stdcall”, “fastcall”, and “cdecl” on non-x86-32 targets](https://github.com/rust-lang/rust/pull/141435) * [Future incompatibility warnings relating to the never type (`!`) are now reported in dependencies](https://github.com/rust-lang/rust/pull/141937) * [Ensure `std::ptr::copy_*` intrinsics also perform the static self-init checks](https://github.com/rust-lang/rust/pull/142575) * [`extern "C"` functions on the `wasm32-unknown-unknown` target now have a standards compliant ABI](https://blog.rust-lang.org/2025/04/04/c-abi-changes-for-wasm32-unknown-unknown/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-1) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Correctly un-remap compiler sources paths with the `rustc-dev` component](https://github.com/rust-lang/rust/pull/142377) [§](https://doc.rust-lang.org/stable/releases.html#version-1880-2025-06-26) Version 1.88.0 (2025-06-26) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-4) Language ----------------------------------------------------------------------- * [Stabilize `#![feature(let_chains)]` in the 2024 edition.](https://github.com/rust-lang/rust/pull/132833) This feature allows `&&`\-chaining `let` statements inside `if` and `while`, allowing intermixture with boolean expressions. The patterns inside the `let` sub-expressions can be irrefutable or refutable. * [Stabilize `#![feature(naked_functions)]`.](https://github.com/rust-lang/rust/pull/134213) Naked functions allow writing functions with no compiler-generated epilogue and prologue, allowing full control over the generated assembly for a particular function. * [Stabilize `#![feature(cfg_boolean_literals)]`.](https://github.com/rust-lang/rust/pull/138632) This allows using boolean literals as `cfg` predicates, e.g. `#[cfg(true)]` and `#[cfg(false)]`. * [Fully de-stabilize the `#[bench]` attribute](https://github.com/rust-lang/rust/pull/134273) . Usage of `#[bench]` without `#![feature(custom_test_frameworks)]` already triggered a deny-by-default future-incompatibility lint since Rust 1.77, but will now become a hard error. * [Add warn-by-default `dangerous_implicit_autorefs` lint against implicit autoref of raw pointer dereference.](https://github.com/rust-lang/rust/pull/123239) The lint [will be bumped to deny-by-default](https://github.com/rust-lang/rust/pull/141661) in the next version of Rust. * [Add `invalid_null_arguments` lint to prevent invalid usage of null pointers.](https://github.com/rust-lang/rust/pull/119220) This lint is uplifted from `clippy::invalid_null_ptr_usage`. * [Change trait impl candidate preference for builtin impls and trivial where-clauses.](https://github.com/rust-lang/rust/pull/138176) * [Check types of generic const parameter defaults](https://github.com/rust-lang/rust/pull/139646) [§](https://doc.rust-lang.org/stable/releases.html#compiler-4) Compiler ----------------------------------------------------------------------- * [Stabilize `-Cdwarf-version` for selecting the version of DWARF debug information to generate.](https://github.com/rust-lang/rust/pull/136926) [§](https://doc.rust-lang.org/stable/releases.html#platform-support-3) Platform Support --------------------------------------------------------------------------------------- * [Demote `i686-pc-windows-gnu` to Tier 2.](https://blog.rust-lang.org/2025/05/26/demoting-i686-pc-windows-gnu/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-4) Libraries ------------------------------------------------------------------------- * [Remove backticks from `#[should_panic]` test failure message.](https://github.com/rust-lang/rust/pull/136160) * [Guarantee that `[T; N]::from_fn` is generated in order of increasing indices.](https://github.com/rust-lang/rust/pull/139099) , for those passing it a stateful closure. * [The libtest flag `--nocapture` is deprecated in favor of the more consistent `--no-capture` flag.](https://github.com/rust-lang/rust/pull/139224) * [Guarantee that `{float}::NAN` is a quiet NaN.](https://github.com/rust-lang/rust/pull/139483) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-4) Stabilized APIs ------------------------------------------------------------------------------------- * [`Cell::update`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.update) * [`impl Default for *const T`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#impl-Default-for-*const+T) * [`impl Default for *mut T`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#impl-Default-for-*mut+T) * [`HashMap::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.extract_if) * [`HashSet::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html#method.extract_if) * [`hint::select_unpredictable`](https://doc.rust-lang.org/stable/std/hint/fn.select_unpredictable.html) * [`proc_macro::Span::line`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.line) * [`proc_macro::Span::column`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.column) * [`proc_macro::Span::start`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.start) * [`proc_macro::Span::end`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.end) * [`proc_macro::Span::file`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.file) * [`proc_macro::Span::local_file`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.local_file) * [`<[T]>::as_chunks`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks) * [`<[T]>::as_chunks_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks_mut) * [`<[T]>::as_chunks_unchecked`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks_unchecked) * [`<[T]>::as_chunks_unchecked_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_chunks_unchecked_mut) * [`<[T]>::as_rchunks`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_rchunks) * [`<[T]>::as_rchunks_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_rchunks_mut) * [`mod ffi::c_str`](https://doc.rust-lang.org/stable/std/ffi/c_str/index.html) These previously stable APIs are now stable in const contexts: * [`NonNull::replace`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.replace) * [`<*mut T>::replace`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.replace) * [`std::ptr::swap_nonoverlapping`](https://doc.rust-lang.org/stable/std/ptr/fn.swap_nonoverlapping.html) * [`Cell::replace`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.replace) * [`Cell::get`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get) * [`Cell::get_mut`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get_mut) * [`Cell::from_mut`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.from_mut) * [`Cell::as_slice_of_cells`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.as_slice_of_cells) [§](https://doc.rust-lang.org/stable/releases.html#cargo-4) Cargo ----------------------------------------------------------------- * [Stabilize automatic garbage collection.](https://github.com/rust-lang/cargo/pull/14287/) * [use `zlib-rs` for gzip compression in rust code](https://github.com/rust-lang/cargo/pull/15417/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-4) Rustdoc --------------------------------------------------------------------- * [Doctests can be ignored based on target names using `ignore-*` attributes.](https://github.com/rust-lang/rust/pull/137096) * [Stabilize the `--test-runtool` and `--test-runtool-arg` CLI options to specify a program (like qemu) and its arguments to run a doctest.](https://github.com/rust-lang/rust/pull/137096) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-4) Compatibility Notes --------------------------------------------------------------------------------------------- * [Finish changing the internal representation of pasted tokens](https://github.com/rust-lang/rust/pull/124141) . Certain invalid declarative macros that were previously accepted in obscure circumstances are now correctly rejected by the compiler. Use of a `tt` fragment specifier can often fix these macros. * [Fully de-stabilize the `#[bench]` attribute](https://github.com/rust-lang/rust/pull/134273) . Usage of `#[bench]` without `#![feature(custom_test_frameworks)]` already triggered a deny-by-default future-incompatibility lint since Rust 1.77, but will now become a hard error. * [Fix borrow checking some always-true patterns.](https://github.com/rust-lang/rust/pull/139042) The borrow checker was overly permissive in some cases, allowing programs that shouldn’t have compiled. * [Update the minimum external LLVM to 19.](https://github.com/rust-lang/rust/pull/139275) * [Make it a hard error to use a vector type with a non-Rust ABI without enabling the required target feature.](https://github.com/rust-lang/rust/pull/139309) [§](https://doc.rust-lang.org/stable/releases.html#version-1870-2025-05-15) Version 1.87.0 (2025-05-15) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-5) Language ----------------------------------------------------------------------- * [Stabilize `asm_goto` feature](https://github.com/rust-lang/rust/pull/133870) * [Allow parsing open beginning ranges (`..EXPR`) after unary operators `!`, `-`, and `*`](https://github.com/rust-lang/rust/pull/134900) . * [Don’t require method impls for methods with `Self: Sized` bounds in `impl`s for unsized types](https://github.com/rust-lang/rust/pull/135480) * [Stabilize `feature(precise_capturing_in_traits)` allowing `use<...>` bounds on return position `impl Trait` in `trait`s](https://github.com/rust-lang/rust/pull/138128) [§](https://doc.rust-lang.org/stable/releases.html#compiler-5) Compiler ----------------------------------------------------------------------- * [x86: make SSE2 required for i686 targets and use it to pass SIMD types](https://github.com/rust-lang/rust/pull/135408) [§](https://doc.rust-lang.org/stable/releases.html#platform-support-4) Platform Support --------------------------------------------------------------------------------------- * [Remove `i586-pc-windows-msvc` target](https://github.com/rust-lang/rust/pull/137957) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-5) Libraries ------------------------------------------------------------------------- * [Stabilize the anonymous pipe API](https://github.com/rust-lang/rust/issues/127154) * [Add support for unbounded left/right shift operations](https://github.com/rust-lang/rust/issues/129375) * [Print pointer metadata in `Debug` impl of raw pointers](https://github.com/rust-lang/rust/pull/135080) * [`Vec::with_capacity` guarantees it allocates with the amount requested, even if `Vec::capacity` returns a different number.](https://github.com/rust-lang/rust/pull/135933) * Most `std::arch` intrinsics which don’t take pointer arguments can now be called from safe code if the caller has the appropriate target features already enabled (https://github.com/rust-lang/stdarch/pull/1714, https://github.com/rust-lang/stdarch/pull/1716, https://github.com/rust-lang/stdarch/pull/1717) * [Undeprecate `env::home_dir`](https://github.com/rust-lang/rust/pull/137327) * [Denote `ControlFlow` as `#[must_use]`](https://github.com/rust-lang/rust/pull/137449) * [Macros such as `assert_eq!` and `vec!` now support `const {...}` expressions](https://github.com/rust-lang/rust/pull/138162) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-5) Stabilized APIs ------------------------------------------------------------------------------------- * [`Vec::extract_if`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.extract_if) * [`vec::ExtractIf`](https://doc.rust-lang.org/stable/std/vec/struct.ExtractIf.html) * [`LinkedList::extract_if`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html#method.extract_if) * [`linked_list::ExtractIf`](https://doc.rust-lang.org/stable/std/collections/linked_list/struct.ExtractIf.html) * [`<[T]>::split_off`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off) * [`<[T]>::split_off_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_mut) * [`<[T]>::split_off_first`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_first) * [`<[T]>::split_off_first_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_first_mut) * [`<[T]>::split_off_last`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_last) * [`<[T]>::split_off_last_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_off_last_mut) * [`String::extend_from_within`](https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.extend_from_within) * [`os_str::Display`](https://doc.rust-lang.org/stable/std/ffi/os_str/struct.Display.html) * [`OsString::display`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.display) * [`OsStr::display`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.display) * [`io::pipe`](https://doc.rust-lang.org/stable/std/io/fn.pipe.html) * [`io::PipeReader`](https://doc.rust-lang.org/stable/std/io/struct.PipeReader.html) * [`io::PipeWriter`](https://doc.rust-lang.org/stable/std/io/struct.PipeWriter.html) * [`impl From for OwnedHandle`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedHandle.html#impl-From%3CPipeReader%3E-for-OwnedHandle) * [`impl From for OwnedHandle`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedHandle.html#impl-From%3CPipeWriter%3E-for-OwnedHandle) * [`impl From for Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html) * [`impl From for Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html#impl-From%3CPipeWriter%3E-for-Stdio) * [`impl From for OwnedFd`](https://doc.rust-lang.org/stable/std/os/fd/struct.OwnedFd.html#impl-From%3CPipeReader%3E-for-OwnedFd) * [`impl From for OwnedFd`](https://doc.rust-lang.org/stable/std/os/fd/struct.OwnedFd.html#impl-From%3CPipeWriter%3E-for-OwnedFd) * [`Box>::write`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.write) * [`impl TryFrom> for String`](https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-TryFrom%3CVec%3Cu8%3E%3E-for-String) * [`<*const T>::offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from_unsigned) * [`<*const T>::byte_offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.byte_offset_from_unsigned) * [`<*mut T>::offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from_unsigned-1) * [`<*mut T>::byte_offset_from_unsigned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.byte_offset_from_unsigned-1) * [`NonNull::offset_from_unsigned`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.offset_from_unsigned) * [`NonNull::byte_offset_from_unsigned`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.byte_offset_from_unsigned) * [`::cast_signed`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.cast_signed) * [`NonZero::::cast_signed`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.cast_signed-5) . * [`::cast_unsigned`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.cast_unsigned) . * [`NonZero::::cast_unsigned`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.cast_unsigned-5) . * [`::is_multiple_of`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.is_multiple_of) * [`::unbounded_shl`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unbounded_shl) * [`::unbounded_shr`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unbounded_shr) * [`::unbounded_shl`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unbounded_shl) * [`::unbounded_shr`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.unbounded_shr) * [`::midpoint`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.midpoint) * [`::from_utf8`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8) * [`::from_utf8_mut`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8_mut) * [`::from_utf8_unchecked`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8_unchecked) * [`::from_utf8_unchecked_mut`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.from_utf8_unchecked_mut) These previously stable APIs are now stable in const contexts: * [`core::str::from_utf8_mut`](https://doc.rust-lang.org/stable/std/str/fn.from_utf8_mut.html) * [`<[T]>::copy_from_slice`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.copy_from_slice) * [`SocketAddr::set_ip`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.set_ip) * [`SocketAddr::set_port`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.set_port) , * [`SocketAddrV4::set_ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.set_ip) * [`SocketAddrV4::set_port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.set_port) , * [`SocketAddrV6::set_ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_ip) * [`SocketAddrV6::set_port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_port) * [`SocketAddrV6::set_flowinfo`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_flowinfo) * [`SocketAddrV6::set_scope_id`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.set_scope_id) * [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) * [`char::is_whitespace`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_whitespace) * [`<[[T; N]]>::as_flattened`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_flattened) * [`<[[T; N]]>::as_flattened_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_flattened_mut) * [`String::into_bytes`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.into_bytes) * [`String::as_str`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_str) * [`String::capacity`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.capacity) * [`String::as_bytes`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_bytes) * [`String::len`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.len) * [`String::is_empty`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.is_empty) * [`String::as_mut_str`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_mut_str) * [`String::as_mut_vec`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.as_mut_vec) * [`Vec::as_ptr`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_ptr) * [`Vec::as_slice`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_slice) * [`Vec::capacity`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.capacity) * [`Vec::len`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.len) * [`Vec::is_empty`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.is_empty) * [`Vec::as_mut_slice`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_mut_slice) * [`Vec::as_mut_ptr`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_mut_ptr) [§](https://doc.rust-lang.org/stable/releases.html#cargo-5) Cargo ----------------------------------------------------------------- * [Add terminal integration via ANSI OSC 9;4 sequences](https://github.com/rust-lang/cargo/pull/14615/) * [chore: bump openssl to v3](https://github.com/rust-lang/cargo/pull/15232/) * [feat(package): add –exclude-lockfile flag](https://github.com/rust-lang/cargo/pull/15234/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-5) Compatibility Notes --------------------------------------------------------------------------------------------- * [Rust now raises an error for macro invocations inside the `#![crate_name]` attribute](https://github.com/rust-lang/rust/pull/127581) * [Unstable fields are now always considered to be inhabited](https://github.com/rust-lang/rust/pull/133889) * [Macro arguments of unary operators followed by open beginning ranges may now be matched differently](https://github.com/rust-lang/rust/pull/134900) * [Make `Debug` impl of raw pointers print metadata if present](https://github.com/rust-lang/rust/pull/135080) * [Warn against function pointers using unsupported ABI strings in dependencies](https://github.com/rust-lang/rust/pull/135767) * [Associated types on `dyn` types are no longer deduplicated](https://github.com/rust-lang/rust/pull/136458) * [Forbid attributes on `..` inside of struct patterns (`let Struct { #[attribute] .. }) =`](https://github.com/rust-lang/rust/pull/136490) * [Make `ptr_cast_add_auto_to_object` lint into hard error](https://github.com/rust-lang/rust/pull/136764) * Many `std::arch` intrinsics are now safe to call in some contexts, there may now be new `unused_unsafe` warnings in existing codebases. * [Limit `width` and `precision` formatting options to 16 bits on all targets](https://github.com/rust-lang/rust/pull/136932) * [Turn order dependent trait objects future incompat warning into a hard error](https://github.com/rust-lang/rust/pull/136968) * [Denote `ControlFlow` as `#[must_use]`](https://github.com/rust-lang/rust/pull/137449) * [Windows: The standard library no longer links `advapi32`, except on win7.](https://github.com/rust-lang/rust/pull/138233) Code such as C libraries that were relying on this assumption may need to explicitly link advapi32. * [Proc macros can no longer observe expanded `cfg(true)` attributes.](https://github.com/rust-lang/rust/pull/138844) * [Start changing the internal representation of pasted tokens](https://github.com/rust-lang/rust/pull/124141) . Certain invalid declarative macros that were previously accepted in obscure circumstances are now correctly rejected by the compiler. Use of a `tt` fragment specifier can often fix these macros. * [Don’t allow flattened format\_args in const.](https://github.com/rust-lang/rust/pull/139624) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-2) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Update to LLVM 20](https://github.com/rust-lang/rust/pull/135763) [§](https://doc.rust-lang.org/stable/releases.html#version-1860-2025-04-03) Version 1.86.0 (2025-04-03) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-6) Language ----------------------------------------------------------------------- * [Stabilize upcasting trait objects to supertraits.](https://github.com/rust-lang/rust/pull/134367) * [Allow safe functions to be marked with the `#[target_feature]` attribute.](https://github.com/rust-lang/rust/pull/134090) * [The `missing_abi` lint now warns-by-default.](https://github.com/rust-lang/rust/pull/132397) * Rust now lints about double negations, to catch cases that might have intended to be a prefix decrement operator (`--x`) as written in other languages. This was previously a clippy lint, `clippy::double_neg`, and is [now available directly in Rust as `double_negations`.](https://github.com/rust-lang/rust/pull/126604) * [More pointers are now detected as definitely not-null based on their alignment in const eval.](https://github.com/rust-lang/rust/pull/133700) * [Empty `repr()` attribute applied to invalid items are now correctly rejected.](https://github.com/rust-lang/rust/pull/133925) * [Inner attributes `#![test]` and `#![rustfmt::skip]` are no longer accepted in more places than intended.](https://github.com/rust-lang/rust/pull/134276) [§](https://doc.rust-lang.org/stable/releases.html#compiler-6) Compiler ----------------------------------------------------------------------- * [Debug-assert that raw pointers are non-null on access.](https://github.com/rust-lang/rust/pull/134424) * [Change `-O` to mean `-C opt-level=3` instead of `-C opt-level=2` to match Cargo’s defaults.](https://github.com/rust-lang/rust/pull/135439) * [Fix emission of `overflowing_literals` under certain macro environments.](https://github.com/rust-lang/rust/pull/136393) [§](https://doc.rust-lang.org/stable/releases.html#platform-support-5) Platform Support --------------------------------------------------------------------------------------- * [Replace `i686-unknown-redox` target with `i586-unknown-redox`.](https://github.com/rust-lang/rust/pull/136698) * [Increase baseline CPU of `i686-unknown-hurd-gnu` to Pentium 4.](https://github.com/rust-lang/rust/pull/136700) * New tier 3 targets: * [`{aarch64-unknown,x86_64-pc}-nto-qnx710_iosock`](https://github.com/rust-lang/rust/pull/133631) . For supporting Neutrino QNX 7.1 with `io-socket` network stack. * [`{aarch64-unknown,x86_64-pc}-nto-qnx800`](https://github.com/rust-lang/rust/pull/133631) . For supporting Neutrino QNX 8.0 (`no_std`\-only). * [`{x86_64,i686}-win7-windows-gnu`](https://github.com/rust-lang/rust/pull/134609) . Intended for backwards compatibility with Windows 7. `{x86_64,i686}-win7-windows-msvc` are the Windows MSVC counterparts that already exist as Tier 3 targets. * [`amdgcn-amd-amdhsa`](https://github.com/rust-lang/rust/pull/134740) . * [`x86_64-pc-cygwin`](https://github.com/rust-lang/rust/pull/134999) . * [`{mips,mipsel}-mti-none-elf`](https://github.com/rust-lang/rust/pull/135074) . Initial bare-metal support. * [`m68k-unknown-none-elf`](https://github.com/rust-lang/rust/pull/135085) . * [`armv7a-nuttx-{eabi,eabihf}`, `aarch64-unknown-nuttx`, and `thumbv7a-nuttx-{eabi,eabihf}`](https://github.com/rust-lang/rust/pull/135757) . Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-6) Libraries ------------------------------------------------------------------------- * The type of `FromBytesWithNulError` in `CStr::from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError>` was [changed from an opaque struct to an enum](https://github.com/rust-lang/rust/pull/134143) , allowing users to examine why the conversion failed. * [Remove `RustcDecodable` and `RustcEncodable`.](https://github.com/rust-lang/rust/pull/134272) * [Deprecate libtest’s `--logfile` option.](https://github.com/rust-lang/rust/pull/134283) * [On recent versions of Windows, `std::fs::remove_file` will now remove read-only files.](https://github.com/rust-lang/rust/pull/134679) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-6) Stabilized APIs ------------------------------------------------------------------------------------- * [`{float}::next_down`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.next_down) * [`{float}::next_up`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.next_up) * [`<[_]>::get_disjoint_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_disjoint_mut) * [`<[_]>::get_disjoint_unchecked_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_disjoint_unchecked_mut) * [`slice::GetDisjointMutError`](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html) * [`HashMap::get_disjoint_mut`](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.get_disjoint_mut) * [`HashMap::get_disjoint_unchecked_mut`](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.get_disjoint_unchecked_mut) * [`NonZero::count_ones`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html#method.count_ones) * [`Vec::pop_if`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pop_if) * [`sync::Once::wait`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.wait) * [`sync::Once::wait_force`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.wait_force) * [`sync::OnceLock::wait`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html#method.wait) These APIs are now stable in const contexts: * [`hint::black_box`](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html) * [`io::Cursor::get_mut`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.get_mut) * [`io::Cursor::set_position`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.set_position) * [`str::is_char_boundary`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.is_char_boundary) * [`str::split_at`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at) * [`str::split_at_checked`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at_checked) * [`str::split_at_mut`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at_mut) * [`str::split_at_mut_checked`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_at_mut_checked) [§](https://doc.rust-lang.org/stable/releases.html#cargo-6) Cargo ----------------------------------------------------------------- * [When merging, replace rather than combine configuration keys that refer to a program path and its arguments.](https://github.com/rust-lang/cargo/pull/15066/) * [Error if both `--package` and `--workspace` are passed but the requested package is missing.](https://github.com/rust-lang/cargo/pull/15071/) This was previously silently ignored, which was considered a bug since missing packages should be reported. * [Deprecate the token argument in `cargo login` to avoid shell history leaks.](https://github.com/rust-lang/cargo/pull/15057/) * [Simplify the implementation of `SourceID` comparisons.](https://github.com/rust-lang/cargo/pull/14980/) This may potentially change behavior if the canonicalized URL compares differently in alternative registries. [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-5) Rustdoc --------------------------------------------------------------------- * [Add a sans-serif font setting.](https://github.com/rust-lang/rust/pull/133636) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-6) Compatibility Notes --------------------------------------------------------------------------------------------- * [The `wasm_c_abi` future compatibility warning is now a hard error.](https://github.com/rust-lang/rust/pull/133951) Users of `wasm-bindgen` should upgrade to at least version 0.2.89, otherwise compilation will fail. * [Remove long-deprecated no-op attributes `#![no_start]` and `#![crate_id]`.](https://github.com/rust-lang/rust/pull/134300) * [The future incompatibility lint `cenum_impl_drop_cast` has been made into a hard error.](https://github.com/rust-lang/rust/pull/135964) This means it is now an error to cast a field-less enum to an integer if the enum implements `Drop`. * [SSE2 is now required for “i686” 32-bit x86 hard-float targets; disabling it causes a warning that will become a hard error eventually.](https://github.com/rust-lang/rust/pull/137037) To compile for pre-SSE2 32-bit x86, use a “i586” target instead. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-3) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Build the rustc on AArch64 Linux with ThinLTO + PGO.](https://github.com/rust-lang/rust/pull/133807) The ARM 64-bit compiler (AArch64) on Linux is now optimized with ThinLTO and PGO, similar to the optimizations we have already performed for the x86-64 compiler on Linux. This should make it up to 30% faster. [§](https://doc.rust-lang.org/stable/releases.html#version-1851-2025-03-18) Version 1.85.1 (2025-03-18) ======================================================================================================= * [Fix the doctest-merging feature of the 2024 Edition.](https://github.com/rust-lang/rust/pull/137899/) * [Relax some `target_feature` checks when generating docs.](https://github.com/rust-lang/rust/pull/137632/) * [Fix errors in `std::fs::rename` on Windows 10, version 1607.](https://github.com/rust-lang/rust/pull/137528/) * [Downgrade bootstrap `cc` to fix custom targets.](https://github.com/rust-lang/rust/pull/137460/) * [Skip submodule updates when building Rust from a source tarball.](https://github.com/rust-lang/rust/pull/137338/) [§](https://doc.rust-lang.org/stable/releases.html#version-1850-2025-02-20) Version 1.85.0 (2025-02-20) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-7) Language ----------------------------------------------------------------------- * [The 2024 Edition is now stable.](https://github.com/rust-lang/rust/pull/133349) See [the edition guide](https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html) for more details. * [Stabilize async closures](https://github.com/rust-lang/rust/pull/132706) See [RFC 3668](https://rust-lang.github.io/rfcs/3668-async-closures.html) for more details. * [Stabilize `#[diagnostic::do_not_recommend]`](https://github.com/rust-lang/rust/pull/132056) * [Add `unpredictable_function_pointer_comparisons` lint to warn against function pointer comparisons](https://github.com/rust-lang/rust/pull/118833) * [Lint on combining `#[no_mangle]` and `#[export_name]` attributes.](https://github.com/rust-lang/rust/pull/131558) [§](https://doc.rust-lang.org/stable/releases.html#compiler-7) Compiler ----------------------------------------------------------------------- * [The unstable flag `-Zpolymorphize` has been removed](https://github.com/rust-lang/rust/pull/133883) , see https://github.com/rust-lang/compiler-team/issues/810 for some background. [§](https://doc.rust-lang.org/stable/releases.html#platform-support-6) Platform Support --------------------------------------------------------------------------------------- * [Promote `powerpc64le-unknown-linux-musl` to tier 2 with host tools](https://github.com/rust-lang/rust/pull/133801) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-7) Libraries ------------------------------------------------------------------------- * [Panics in the standard library now have a leading `library/` in their path](https://github.com/rust-lang/rust/pull/132390) * [`std::env::home_dir()` on Windows now ignores the non-standard `$HOME` environment variable](https://github.com/rust-lang/rust/pull/132515) It will be un-deprecated in a subsequent release. * [Add `AsyncFn*` to the prelude in all editions.](https://github.com/rust-lang/rust/pull/132611) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-7) Stabilized APIs ------------------------------------------------------------------------------------- * [`BuildHasherDefault::new`](https://doc.rust-lang.org/stable/std/hash/struct.BuildHasherDefault.html#method.new) * [`ptr::fn_addr_eq`](https://doc.rust-lang.org/std/ptr/fn.fn_addr_eq.html) * [`io::ErrorKind::QuotaExceeded`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.QuotaExceeded) * [`io::ErrorKind::CrossesDevices`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.CrossesDevices) * [`{float}::midpoint`](https://doc.rust-lang.org/core/primitive.f32.html#method.midpoint) * [Unsigned `{integer}::midpoint`](https://doc.rust-lang.org/std/primitive.u64.html#method.midpoint) * [`NonZeroU*::midpoint`](https://doc.rust-lang.org/std/num/type.NonZeroU32.html#method.midpoint) * [impl `std::iter::Extend` for tuples with arity 1 through 12](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#impl-Extend%3C(A,)%3E-for-(EA,)) * [`FromIterator<(A, ...)>` for tuples with arity 1 through 12](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#impl-FromIterator%3C(EA,)%3E-for-(A,)) * [`std::task::Waker::noop`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html#method.noop) These APIs are now stable in const contexts: * [`mem::size_of_val`](https://doc.rust-lang.org/stable/std/mem/fn.size_of_val.html) * [`mem::align_of_val`](https://doc.rust-lang.org/stable/std/mem/fn.align_of_val.html) * [`Layout::for_value`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.for_value) * [`Layout::align_to`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.align_to) * [`Layout::pad_to_align`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.pad_to_align) * [`Layout::extend`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.extend) * [`Layout::array`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.array) * [`std::mem::swap`](https://doc.rust-lang.org/stable/std/mem/fn.swap.html) * [`std::ptr::swap`](https://doc.rust-lang.org/stable/std/ptr/fn.swap.html) * [`NonNull::new`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.new) * [`HashMap::with_hasher`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.with_hasher) * [`HashSet::with_hasher`](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html#method.with_hasher) * [`BuildHasherDefault::new`](https://doc.rust-lang.org/stable/std/hash/struct.BuildHasherDefault.html#method.new) * [`::recip`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.recip) * [`::to_degrees`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.to_degrees) * [`::to_radians`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.to_radians) * [`::max`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.max) * [`::min`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.min) * [`::clamp`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.clamp) * [`::abs`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.abs) * [`::signum`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.signum) * [`::copysign`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.copysign) * [`MaybeUninit::write`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.write) [§](https://doc.rust-lang.org/stable/releases.html#cargo-7) Cargo ----------------------------------------------------------------- * [Add future-incompatibility warning against keywords in cfgs and add raw-idents](https://github.com/rust-lang/cargo/pull/14671/) * [Stabilize higher precedence trailing flags](https://github.com/rust-lang/cargo/pull/14900/) * [Pass `CARGO_CFG_FEATURE` to build scripts](https://github.com/rust-lang/cargo/pull/14902/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-6) Rustdoc --------------------------------------------------------------------- * [Doc comment on impl blocks shows the first line, even when the impl block is collapsed](https://github.com/rust-lang/rust/pull/132155) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-7) Compatibility Notes --------------------------------------------------------------------------------------------- * [`rustc` no longer treats the `test` cfg as a well known check-cfg](https://github.com/rust-lang/rust/pull/131729) , instead it is up to the build systems and users of `--check-cfg`[1](https://doc.rust-lang.org/stable/releases.html#fn1) to set it as a well known cfg using `--check-cfg=cfg(test)`. This is done to enable build systems like Cargo to set it conditionally, as not all source files are suitable for unit tests. [Cargo (for now) unconditionally sets the `test` cfg as a well known cfg](https://github.com/rust-lang/cargo/pull/14963) . * [Disable potentially incorrect type inference if there are trivial and non-trivial where-clauses](https://github.com/rust-lang/rust/pull/132325) * `std::env::home_dir()` has been deprecated for years, because it can give surprising results in some Windows configurations if the `HOME` environment variable is set (which is not the normal configuration on Windows). We had previously avoided changing its behavior, out of concern for compatibility with code depending on this non-standard configuration. Given how long this function has been deprecated, we’re now fixing its behavior as a bugfix. A subsequent release will remove the deprecation for this function. * [Make `core::ffi::c_char` signedness more closely match that of the platform-default `char`](https://github.com/rust-lang/rust/pull/132975) This changed `c_char` from an `i8` to `u8` or vice versa on many Tier 2 and 3 targets (mostly Arm and RISC-V embedded targets). The new definition may result in compilation failures but fixes compatibility issues with C. The `libc` crate matches this change as of its 0.2.169 release. * [When compiling a nested `macro_rules` macro from an external crate, the content of the inner `macro_rules` is now built with the edition of the external crate, not the local crate.](https://github.com/rust-lang/rust/pull/133274) * [Increase `sparcv9-sun-solaris` and `x86_64-pc-solaris` Solaris baseline to 11.4.](https://github.com/rust-lang/rust/pull/133293) * [Show `abi_unsupported_vector_types` lint in future breakage reports](https://github.com/rust-lang/rust/pull/133374) * [Error if multiple super-trait instantiations of `dyn Trait` need associated types to be specified but only one is provided](https://github.com/rust-lang/rust/pull/133392) * [Change `powerpc64-ibm-aix` default `codemodel` to large](https://github.com/rust-lang/rust/pull/133811) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-4) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Build `x86_64-unknown-linux-gnu` with LTO for C/C++ code (e.g., `jemalloc`)](https://github.com/rust-lang/rust/pull/134690) [§](https://doc.rust-lang.org/stable/releases.html#version-1841-2025-01-30) Version 1.84.1 (2025-01-30) ======================================================================================================= * [Fix ICE 132920 in duplicate-crate diagnostics.](https://github.com/rust-lang/rust/pull/133304/) * [Fix errors for overlapping impls in incremental rebuilds.](https://github.com/rust-lang/rust/pull/133828/) * [Fix slow compilation related to the next-generation trait solver.](https://github.com/rust-lang/rust/pull/135618/) * [Fix debuginfo when LLVM’s location discriminator value limit is exceeded.](https://github.com/rust-lang/rust/pull/135643/) * Fixes for building Rust from source: * [Only try to distribute `llvm-objcopy` if llvm tools are enabled.](https://github.com/rust-lang/rust/pull/134240/) * [Add Profile Override for Non-Git Sources.](https://github.com/rust-lang/rust/pull/135433/) * [Resolve symlinks of LLVM tool binaries before copying them.](https://github.com/rust-lang/rust/pull/135585/) * [Make it possible to use ci-rustc on tarball sources.](https://github.com/rust-lang/rust/pull/135722/) [§](https://doc.rust-lang.org/stable/releases.html#version-1840-2025-01-09) Version 1.84.0 (2025-01-09) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-8) Language ----------------------------------------------------------------------- * [Allow `#[deny]` inside `#[forbid]` as a no-op](https://github.com/rust-lang/rust/pull/121560/) * [Show a warning when `-Ctarget-feature` is used to toggle features that can lead to unsoundness due to ABI mismatches](https://github.com/rust-lang/rust/pull/129884) * [Use the next-generation trait solver in coherence](https://github.com/rust-lang/rust/pull/130654) * [Allow coercions to drop the principal of trait objects](https://github.com/rust-lang/rust/pull/131857) * [Support `/` as the path separator for `include!()` in all cases on Windows](https://github.com/rust-lang/rust/pull/125205) * [Taking a raw ref (`raw (const|mut)`) of a deref of a pointer (`*ptr`) is now safe](https://github.com/rust-lang/rust/pull/129248) * [Stabilize s390x inline assembly](https://github.com/rust-lang/rust/pull/131258) * [Stabilize Arm64EC inline assembly](https://github.com/rust-lang/rust/pull/131781) * [Lint against creating pointers to immediately dropped temporaries](https://github.com/rust-lang/rust/pull/128985) * [Execute drop glue when unwinding in an `extern "C"` function](https://github.com/rust-lang/rust/pull/129582) [§](https://doc.rust-lang.org/stable/releases.html#compiler-8) Compiler ----------------------------------------------------------------------- * [Add `--print host-tuple` flag to print the host target tuple and affirm the “target tuple” terminology over “target triple”](https://github.com/rust-lang/rust/pull/125579) * [Declaring functions with a calling convention not supported on the current target now triggers a hard error](https://github.com/rust-lang/rust/pull/129935) * [Set up indirect access to external data for `loongarch64-unknown-linux-{musl,ohos}`](https://github.com/rust-lang/rust/pull/131583) * [Enable XRay instrumentation for LoongArch Linux targets](https://github.com/rust-lang/rust/pull/131818) * [Extend the `unexpected_cfgs` lint to also warn in external macros](https://github.com/rust-lang/rust/pull/132577) * [Stabilize WebAssembly `multivalue`, `reference-types`, and `tail-call` target features](https://github.com/rust-lang/rust/pull/131080) * [Added Tier 2 support for the `wasm32v1-none` target](https://github.com/rust-lang/rust/pull/131487) [§](https://doc.rust-lang.org/stable/releases.html#libraries-8) Libraries ------------------------------------------------------------------------- * [Implement `From<&mut {slice}>` for `Box/Rc/Arc<{slice}>`](https://github.com/rust-lang/rust/pull/129329) * [Move `::copysign`, `::abs`, `::signum` to `core`](https://github.com/rust-lang/rust/pull/131304) * [Add `LowerExp` and `UpperExp` implementations to `NonZero`](https://github.com/rust-lang/rust/pull/131377) * [Implement `FromStr` for `CString` and `TryFrom` for `String`](https://github.com/rust-lang/rust/pull/130608) * [`std::os::darwin` has been made public](https://github.com/rust-lang/rust/pull/123723) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-8) Stabilized APIs ------------------------------------------------------------------------------------- * [`Ipv6Addr::is_unique_local`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.is_unique_local) * [`Ipv6Addr::is_unicast_link_local`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.is_unicast_link_local) * [`core::ptr::with_exposed_provenance`](https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance.html) * [`core::ptr::with_exposed_provenance_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance_mut.html) * [`::addr`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.addr) * [`::expose_provenance`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.expose_provenance) * [`::with_addr`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.with_addr) * [`::map_addr`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.map_addr) * [`::isqrt`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.isqrt) * [`::checked_isqrt`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.checked_isqrt) * [`::isqrt`](https://doc.rust-lang.org/stable/core/primitive.u32.html#method.isqrt) * [`NonZero::isqrt`](https://doc.rust-lang.org/stable/core/num/struct.NonZero.html#impl-NonZero%3Cu128%3E/method.isqrt) * [`core::ptr::without_provenance`](https://doc.rust-lang.org/stable/core/ptr/fn.without_provenance.html) * [`core::ptr::without_provenance_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.without_provenance_mut.html) * [`core::ptr::dangling`](https://doc.rust-lang.org/stable/core/ptr/fn.dangling.html) * [`core::ptr::dangling_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.dangling_mut.html) * [`Pin::as_deref_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.as_deref_mut) These APIs are now stable in const contexts * [`AtomicBool::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicBool.html#method.from_ptr) * [`AtomicPtr::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicPtr.html#method.from_ptr) * [`AtomicU8::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU8.html#method.from_ptr) * [`AtomicU16::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU16.html#method.from_ptr) * [`AtomicU32::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU32.html#method.from_ptr) * [`AtomicU64::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicU64.html#method.from_ptr) * [`AtomicUsize::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicUsize.html#method.from_ptr) * [`AtomicI8::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI8.html#method.from_ptr) * [`AtomicI16::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI16.html#method.from_ptr) * [`AtomicI32::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI32.html#method.from_ptr) * [`AtomicI64::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicI64.html#method.from_ptr) * [`AtomicIsize::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicIsize.html#method.from_ptr) * [`::is_null`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_null-1) * [`::as_ref`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.as_ref-1) * [`::as_mut`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.as_mut) * [`Pin::new`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.new) * [`Pin::new_unchecked`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.new_unchecked) * [`Pin::get_ref`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.get_ref) * [`Pin::into_ref`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.into_ref) * [`Pin::get_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.get_mut) * [`Pin::get_unchecked_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.get_unchecked_mut) * [`Pin::static_ref`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.static_ref) * [`Pin::static_mut`](https://doc.rust-lang.org/stable/core/pin/struct.Pin.html#method.static_mut) [§](https://doc.rust-lang.org/stable/releases.html#cargo-8) Cargo ----------------------------------------------------------------- * [Stabilize MSRV-aware resolver config](https://github.com/rust-lang/cargo/pull/14639/) * [Stabilize resolver v3](https://github.com/rust-lang/cargo/pull/14754/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-7) Rustdoc --------------------------------------------------------------------- * [rustdoc-search: improve type-driven search](https://github.com/rust-lang/rust/pull/127589) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-8) Compatibility Notes --------------------------------------------------------------------------------------------- * [Enable by default the `LSX` target feature for LoongArch Linux targets](https://github.com/rust-lang/rust/pull/132140) * [The unstable `-Zprofile` flag (“gcov-style” coverage instrumentation) has been removed.](https://github.com/rust-lang/rust/pull/131829) This does not affect the stable flags for coverage instrumentation (`-Cinstrument-coverage`) and profile-guided optimization (`-Cprofile-generate`, `-Cprofile-use`), which are unrelated and remain available. * Support for the target named `wasm32-wasi` has been removed as the target is now named `wasm32-wasip1`. This completes the [transition](https://github.com/rust-lang/compiler-team/issues/607) [plan](https://github.com/rust-lang/compiler-team/issues/695) for this target following [the introduction of `wasm32-wasip1`](https://github.com/rust-lang/rust/pull/120468) in Rust 1.78. Compiler warnings on [use of `wasm32-wasi`](https://github.com/rust-lang/rust/pull/126662) introduced in Rust 1.81 are now gone as well as the target is removed. * [The syntax `&pin (mut|const) T` is now parsed as a type which in theory could affect macro expansion results in some edge cases](https://github.com/rust-lang/rust/pull/130635#issuecomment-2375462821) * [Legacy syntax for calling `std::arch` functions is no longer permitted to declare items or bodies (such as closures, inline consts, or async blocks).](https://github.com/rust-lang/rust/pull/130443#issuecomment-2445678945) * [Declaring functions with a calling convention not supported on the current target now triggers a hard error](https://github.com/rust-lang/rust/pull/129935) * [The next-generation trait solver is now enabled for coherence, fixing multiple soundness issues](https://github.com/rust-lang/rust/pull/130654) [§](https://doc.rust-lang.org/stable/releases.html#version-1830-2024-11-28) Version 1.83.0 (2024-11-28) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-9) Language ----------------------------------------------------------------------- * [Stabilize `&mut`, `*mut`, `&Cell`, and `*const Cell` in const.](https://github.com/rust-lang/rust/pull/129195) * [Allow creating references to statics in `const` initializers.](https://github.com/rust-lang/rust/pull/129759) * [Implement raw lifetimes and labels (`'r#ident`).](https://github.com/rust-lang/rust/pull/126452) * [Define behavior when atomic and non-atomic reads race.](https://github.com/rust-lang/rust/pull/128778) * [Non-exhaustive structs may now be empty.](https://github.com/rust-lang/rust/pull/128934) * [Disallow implicit coercions from places of type `!`](https://github.com/rust-lang/rust/pull/129392) * [`const extern` functions can now be defined for other calling conventions.](https://github.com/rust-lang/rust/pull/129753) * [Stabilize `expr_2021` macro fragment specifier in all editions.](https://github.com/rust-lang/rust/pull/129972) * [The `non_local_definitions` lint now fires on less code and warns by default.](https://github.com/rust-lang/rust/pull/127117) [§](https://doc.rust-lang.org/stable/releases.html#compiler-9) Compiler ----------------------------------------------------------------------- * [Deprecate unsound `-Csoft-float` flag.](https://github.com/rust-lang/rust/pull/129897) * Add many new tier 3 targets: * [`aarch64_unknown_nto_qnx700`](https://github.com/rust-lang/rust/pull/127897) * [`arm64e-apple-tvos`](https://github.com/rust-lang/rust/pull/130614) * [`armv7-rtems-eabihf`](https://github.com/rust-lang/rust/pull/127021) * [`loongarch64-unknown-linux-ohos`](https://github.com/rust-lang/rust/pull/130750) * [`riscv32-wrs-vxworks` and `riscv64-wrs-vxworks`](https://github.com/rust-lang/rust/pull/130549) * [`riscv32{e|em|emc}-unknown-none-elf`](https://github.com/rust-lang/rust/pull/130555) * [`x86_64-unknown-hurd-gnu`](https://github.com/rust-lang/rust/pull/128345) * [`x86_64-unknown-trusty`](https://github.com/rust-lang/rust/pull/130453) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-9) Libraries ------------------------------------------------------------------------- * [Implement `PartialEq` for `ExitCode`.](https://github.com/rust-lang/rust/pull/127633) * [Document that `catch_unwind` can deal with foreign exceptions without UB, although the exact behavior is unspecified.](https://github.com/rust-lang/rust/pull/128321) * [Implement `Default` for `HashMap`/`HashSet` iterators that don’t already have it.](https://github.com/rust-lang/rust/pull/128711) * [Bump Unicode to version 16.0.0.](https://github.com/rust-lang/rust/pull/130183) * [Change documentation of `ptr::add`/`sub` to not claim equivalence with `offset`.](https://github.com/rust-lang/rust/pull/130229) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-9) Stabilized APIs ------------------------------------------------------------------------------------- * [`BufRead::skip_until`](https://doc.rust-lang.org/stable/std/io/trait.BufRead.html#method.skip_until) * [`ControlFlow::break_value`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.break_value) * [`ControlFlow::continue_value`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.continue_value) * [`ControlFlow::map_break`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.map_break) * [`ControlFlow::map_continue`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.map_continue) * [`DebugList::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugList.html#method.finish_non_exhaustive) * [`DebugMap::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugMap.html#method.finish_non_exhaustive) * [`DebugSet::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugSet.html#method.finish_non_exhaustive) * [`DebugTuple::finish_non_exhaustive`](https://doc.rust-lang.org/stable/core/fmt/struct.DebugTuple.html#method.finish_non_exhaustive) * [`ErrorKind::ArgumentListTooLong`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ArgumentListTooLong) * [`ErrorKind::Deadlock`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.Deadlock) * [`ErrorKind::DirectoryNotEmpty`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.DirectoryNotEmpty) * [`ErrorKind::ExecutableFileBusy`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ExecutableFileBusy) * [`ErrorKind::FileTooLarge`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.FileTooLarge) * [`ErrorKind::HostUnreachable`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.HostUnreachable) * [`ErrorKind::IsADirectory`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.IsADirectory) * [`ErrorKind::NetworkDown`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NetworkDown) * [`ErrorKind::NetworkUnreachable`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NetworkUnreachable) * [`ErrorKind::NotADirectory`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotADirectory) * [`ErrorKind::NotSeekable`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotSeekable) * [`ErrorKind::ReadOnlyFilesystem`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ReadOnlyFilesystem) * [`ErrorKind::ResourceBusy`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ResourceBusy) * [`ErrorKind::StaleNetworkFileHandle`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.StaleNetworkFileHandle) * [`ErrorKind::StorageFull`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.StorageFull) * [`ErrorKind::TooManyLinks`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.TooManyLinks) * [`Option::get_or_insert_default`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.get_or_insert_default) * [`Waker::data`](https://doc.rust-lang.org/stable/core/task/struct.Waker.html#method.data) * [`Waker::new`](https://doc.rust-lang.org/stable/core/task/struct.Waker.html#method.new) * [`Waker::vtable`](https://doc.rust-lang.org/stable/core/task/struct.Waker.html#method.vtable) * [`char::MIN`](https://doc.rust-lang.org/stable/core/primitive.char.html#associatedconstant.MIN) * [`hash_map::Entry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.insert_entry) * [`hash_map::VacantEntry::insert_entry`](https://doc.rust-lang.org/stable/std/collections/hash_map/struct.VacantEntry.html#method.insert_entry) These APIs are now stable in const contexts: * [`Cell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.Cell.html#method.into_inner) * [`Duration::as_secs_f32`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.as_secs_f32) * [`Duration::as_secs_f64`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.as_secs_f64) * [`Duration::div_duration_f32`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.div_duration_f32) * [`Duration::div_duration_f64`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.div_duration_f64) * [`MaybeUninit::as_mut_ptr`](https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#method.as_mut_ptr) * [`NonNull::as_mut`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.as_mut) * [`NonNull::copy_from`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_from) * [`NonNull::copy_from_nonoverlapping`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_from_nonoverlapping) * [`NonNull::copy_to`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_to) * [`NonNull::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.copy_to_nonoverlapping) * [`NonNull::slice_from_raw_parts`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.slice_from_raw_parts) * [`NonNull::write`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.write) * [`NonNull::write_bytes`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.write_bytes) * [`NonNull::write_unaligned`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.write_unaligned) * [`OnceCell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.OnceCell.html#method.into_inner) * [`Option::as_mut`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.as_mut) * [`Option::expect`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.expect) * [`Option::replace`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.replace) * [`Option::take`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.take) * [`Option::unwrap`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.unwrap) * [`Option::unwrap_unchecked`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.unwrap_unchecked) * [`Option::<&_>::copied`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.copied) * [`Option::<&mut _>::copied`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.copied-1) * [`Option::>::flatten`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.flatten) * [`Option::>::transpose`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.transpose) * [`RefCell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.RefCell.html#method.into_inner) * [`Result::as_mut`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.as_mut) * [`Result::<&_, _>::copied`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.copied) * [`Result::<&mut _, _>::copied`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.copied-1) * [`Result::, _>::transpose`](https://doc.rust-lang.org/stable/core/result/enum.Result.html#method.transpose) * [`UnsafeCell::get_mut`](https://doc.rust-lang.org/stable/core/cell/struct.UnsafeCell.html#method.get_mut) * [`UnsafeCell::into_inner`](https://doc.rust-lang.org/stable/core/cell/struct.UnsafeCell.html#method.into_inner) * [`array::from_mut`](https://doc.rust-lang.org/stable/core/array/fn.from_mut.html) * [`char::encode_utf8`](https://doc.rust-lang.org/stable/core/primitive.char.html#method.encode_utf8) * [`{float}::classify`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.classify) * [`{float}::is_finite`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_finite) * [`{float}::is_infinite`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_infinite) * [`{float}::is_nan`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_nan) * [`{float}::is_normal`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_normal) * [`{float}::is_sign_negative`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_sign_negative) * [`{float}::is_sign_positive`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_sign_positive) * [`{float}::is_subnormal`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.is_subnormal) * [`{float}::from_bits`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_bits) * [`{float}::from_be_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_be_bytes) * [`{float}::from_le_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_le_bytes) * [`{float}::from_ne_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.from_ne_bytes) * [`{float}::to_bits`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_bits) * [`{float}::to_be_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_be_bytes) * [`{float}::to_le_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_le_bytes) * [`{float}::to_ne_bytes`](https://doc.rust-lang.org/stable/core/primitive.f64.html#method.to_ne_bytes) * [`mem::replace`](https://doc.rust-lang.org/stable/core/mem/fn.replace.html) * [`ptr::replace`](https://doc.rust-lang.org/stable/core/ptr/fn.replace.html) * [`ptr::slice_from_raw_parts_mut`](https://doc.rust-lang.org/stable/core/ptr/fn.slice_from_raw_parts_mut.html) * [`ptr::write`](https://doc.rust-lang.org/stable/core/ptr/fn.write.html) * [`ptr::write_unaligned`](https://doc.rust-lang.org/stable/core/ptr/fn.write_unaligned.html) * [`<*const _>::copy_to`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to) * [`<*const _>::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to_nonoverlapping) * [`<*mut _>::copy_from`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_from) * [`<*mut _>::copy_from_nonoverlapping`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_from_nonoverlapping) * [`<*mut _>::copy_to`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to-1) * [`<*mut _>::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.copy_to_nonoverlapping-1) * [`<*mut _>::write`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.write) * [`<*mut _>::write_bytes`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.write_bytes) * [`<*mut _>::write_unaligned`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.write_unaligned) * [`slice::from_mut`](https://doc.rust-lang.org/stable/core/slice/fn.from_mut.html) * [`slice::from_raw_parts_mut`](https://doc.rust-lang.org/stable/core/slice/fn.from_raw_parts_mut.html) * [`<[_]>::first_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.first_mut) * [`<[_]>::last_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.last_mut) * [`<[_]>::first_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.first_chunk_mut) * [`<[_]>::last_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.last_chunk_mut) * [`<[_]>::split_at_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut) * [`<[_]>::split_at_mut_checked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut_checked) * [`<[_]>::split_at_mut_unchecked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut_unchecked) * [`<[_]>::split_first_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_first_mut) * [`<[_]>::split_last_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_last_mut) * [`<[_]>::split_first_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_first_chunk_mut) * [`<[_]>::split_last_chunk_mut`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_last_chunk_mut) * [`str::as_bytes_mut`](https://doc.rust-lang.org/stable/core/primitive.str.html#method.as_bytes_mut) * [`str::as_mut_ptr`](https://doc.rust-lang.org/stable/core/primitive.str.html#method.as_mut_ptr) * [`str::from_utf8_unchecked_mut`](https://doc.rust-lang.org/stable/core/str/fn.from_utf8_unchecked_mut.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-9) Cargo ----------------------------------------------------------------- * [Introduced a new `CARGO_MANIFEST_PATH` environment variable, similar to `CARGO_MANIFEST_DIR` but pointing directly to the manifest file.](https://github.com/rust-lang/cargo/pull/14404/) * [Added `package.autolib` to the manifest, allowing `[lib]` auto-discovery to be disabled.](https://github.com/rust-lang/cargo/pull/14591/) * [Declare support level for each crate in Cargo’s Charter / crate docs.](https://github.com/rust-lang/cargo/pull/14600/) * [Declare new Intentional Artifacts as ‘small’ changes.](https://github.com/rust-lang/cargo/pull/14599/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-8) Rustdoc --------------------------------------------------------------------- * [The sidebar / hamburger menu table of contents now includes the `# headers` from the main item’s doc comment](https://github.com/rust-lang/rust/pull/120736) . This is similar to a third-party feature provided by the rustdoc-search-enhancements browser extension. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-9) Compatibility Notes --------------------------------------------------------------------------------------------- * [Warn against function pointers using unsupported ABI strings.](https://github.com/rust-lang/rust/pull/128784) * [Check well-formedness of the source type’s signature in fn pointer casts.](https://github.com/rust-lang/rust/pull/129021) This partly closes a soundness hole that comes when casting a function item to function pointer * [Use equality instead of subtyping when resolving type dependent paths.](https://github.com/rust-lang/rust/pull/129073) * Linking on macOS now correctly includes Rust’s default deployment target. Due to a linker bug, you might have to pass `MACOSX_DEPLOYMENT_TARGET` or fix your `#[link]` attributes to point to the correct frameworks. See [https://github.com/rust-lang/rust/pull/129369](https://github.com/rust-lang/rust/pull/129369) . * [Rust will now correctly raise an error for `repr(Rust)` written on non-`struct`/`enum`/`union` items, since it previous did not have any effect.](https://github.com/rust-lang/rust/pull/129422) * The future incompatibility lint `deprecated_cfg_attr_crate_type_name` [has been made into a hard error](https://github.com/rust-lang/rust/pull/129670) . It was used to deny usage of `#![crate_type]` and `#![crate_name]` attributes in `#![cfg_attr]`, which required a hack in the compiler to be able to change the used crate type and crate name after cfg expansion. Users can use `--crate-type` instead of `#![cfg_attr(..., crate_type = "...")]` and `--crate-name` instead of `#![cfg_attr(..., crate_name = "...")]` when running `rustc`/`cargo rustc` on the command line. Use of those two attributes outside of `#![cfg_attr]` continue to be fully supported. * Until now, paths into the sysroot were always prefixed with `/rustc/$hash` in diagnostics, codegen, backtrace, e.g. thread 'main' panicked at 'hello world', map-panic.rs:2:50 stack backtrace: 0: std::panicking::begin_panic at /rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/std/src/panicking.rs:616:12 1: map_panic::main::{{closure}} at ./map-panic.rs:2:50 2: core::option::Option::map at /rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/core/src/option.rs:929:29 3: map_panic::main at ./map-panic.rs:2:30 4: core::ops::function::FnOnce::call_once at /rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/core/src/ops/function.rs:248:5 note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. [](https://play.rust-lang.org/?code=thread+%27main%27+panicked+at+%27hello+world%27,+map-panic.rs:2:50%0Astack+backtrace:%0A+++0:+std::panicking::begin_panic%0A+++++++++++++at+/rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/std/src/panicking.rs:616:12%0A+++1:+map_panic::main::%7B%7Bclosure%7D%7D%0A+++++++++++++at+./map-panic.rs:2:50%0A+++2:+core::option::Option%3CT%3E::map%0A+++++++++++++at+/rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/core/src/option.rs:929:29%0A+++3:+map_panic::main%0A+++++++++++++at+./map-panic.rs:2:30%0A+++4:+core::ops::function::FnOnce::call_once%0A+++++++++++++at+/rustc/a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52/library/core/src/ops/function.rs:248:5%0Anote:+Some+details+are+omitted,+run+with+%60RUST_BACKTRACE=full%60+for+a+verbose+backtrace.&edition=2015 "Run code") [RFC 3127 said](https://rust-lang.github.io/rfcs/3127-trim-paths.html#changing-handling-of-sysroot-path-in-rustc) > We want to change this behaviour such that, when `rust-src` source files can be discovered, the virtual path is discarded and therefore the local path will be embedded, unless there is a `--remap-path-prefix` that causes this local path to be remapped in the usual way. [#129687](https://github.com/rust-lang/rust/pull/129687) implements this behaviour, when `rust-src` is present at compile time, `rustc` replaces `/rustc/$hash` with a real path into the local `rust-src` component with best effort. To sanitize this, users must explicitly supply `--remap-path-prefix==foo` or not have the `rust-src` component installed. * The allow-by-default `missing_docs` lint used to disable itself when invoked through `rustc --test`/`cargo test`, resulting in `#[expect(missing_docs)]` emitting false positives due to the expectation being wrongly unfulfilled. This behavior [has now been removed](https://github.com/rust-lang/rust/pull/130025) , which allows `#[expect(missing_docs)]` to be fulfilled in all scenarios, but will also report new `missing_docs` diagnostics for publicly reachable `#[cfg(test)]` items, [integration test](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#integration-tests) crate-level documentation, and publicly reachable items in integration tests. * [The `armv8r-none-eabihf` target now uses the Armv8-R required set of floating-point features.](https://github.com/rust-lang/rust/pull/130295) * [Fix a soundness bug where rustc wouldn’t detect unconstrained higher-ranked lifetimes in a `dyn Trait`’s associated types that occur due to supertraits.](https://github.com/rust-lang/rust/pull/130367) * [Update the minimum external LLVM version to 18.](https://github.com/rust-lang/rust/pull/130487) * [Remove `aarch64-fuchsia` and `x86_64-fuchsia` target aliases in favor of `aarch64-unknown-fuchsia` and `x86_64-unknown-fuchsia` respectively.](https://github.com/rust-lang/rust/pull/130657) * [The ABI-level exception class of a Rust panic is now encoded with native-endian bytes, so it is legible in hex dumps.](https://github.com/rust-lang/rust/pull/130897) * [Visual Studio 2013 is no longer supported for MSVC targets.](https://github.com/rust-lang/rust/pull/131070) * [The sysroot no longer contains the `std` dynamic library in its top-level `lib/` dir.](https://github.com/rust-lang/rust/pull/131188) [§](https://doc.rust-lang.org/stable/releases.html#version-1820-2024-10-17) Version 1.82.0 (2024-10-17) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-10) Language ------------------------------------------------------------------------ * [Don’t make statement nonterminals match pattern nonterminals](https://github.com/rust-lang/rust/pull/120221/) * [Patterns matching empty types can now be omitted in common cases](https://github.com/rust-lang/rust/pull/122792) * [Enforce supertrait outlives obligations when using trait impls](https://github.com/rust-lang/rust/pull/124336) * [`addr_of(_mut)!` macros and the newly stabilized `&raw (const|mut)` are now safe to use with all static items](https://github.com/rust-lang/rust/pull/125834) * [size\_of\_val\_raw: for length 0 this is safe to call](https://github.com/rust-lang/rust/pull/126152/) * [Reorder trait bound modifiers _after_ `for<...>` binder in trait bounds](https://github.com/rust-lang/rust/pull/127054/) * [Stabilize `+ use<'lt>` opaque type precise capturing (RFC 3617)](https://github.com/rust-lang/rust/pull/127672) * [Stabilize `&raw const` and `&raw mut` operators (RFC 2582)](https://github.com/rust-lang/rust/pull/127679) * [Stabilize unsafe extern blocks (RFC 3484)](https://github.com/rust-lang/rust/pull/127921) * [Stabilize nested field access in `offset_of!`](https://github.com/rust-lang/rust/pull/128284) * [Do not require `T` to be live when dropping `[T; 0]`](https://github.com/rust-lang/rust/pull/128438) * [Stabilize `const` operands in inline assembly](https://github.com/rust-lang/rust/pull/128570) * [Stabilize floating-point arithmetic in `const fn`](https://github.com/rust-lang/rust/pull/128596) * [Stabilize explicit opt-in to unsafe attributes](https://github.com/rust-lang/rust/pull/128771) * [Document NaN bit patterns guarantees](https://github.com/rust-lang/rust/pull/129559) [§](https://doc.rust-lang.org/stable/releases.html#compiler-10) Compiler ------------------------------------------------------------------------ * [Promote riscv64gc-unknown-linux-musl to tier 2](https://github.com/rust-lang/rust/pull/122049) * [Promote Mac Catalyst targets `aarch64-apple-ios-macabi` and `x86_64-apple-ios-macabi` to Tier 2, and ship them with rustup](https://github.com/rust-lang/rust/pull/126450) * [Add tier 3 NuttX based targets for RISC-V and ARM](https://github.com/rust-lang/rust/pull/127755) * [Add tier 3 powerpc-unknown-linux-muslspe target](https://github.com/rust-lang/rust/pull/127905) * [Improved diagnostics to explain why a pattern is unreachable](https://github.com/rust-lang/rust/pull/128034) * [The compiler now triggers the unreachable code warning properly for async functions that don’t return/are `-> !`](https://github.com/rust-lang/rust/pull/128443) * [Promote `aarch64-apple-darwin` to Tier 1](https://github.com/rust-lang/rust/pull/128592) * [Add Trusty OS target `aarch64-unknown-trusty` and `armv7-unknown-trusty` as tier 3 targets](https://github.com/rust-lang/rust/pull/129490) * [Promote `wasm32-wasip2` to Tier 2.](https://github.com/rust-lang/rust/pull/126967/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-10) Libraries -------------------------------------------------------------------------- * [Generalize `{Rc,Arc}::make_mut()` to `Path`, `OsStr`, and `CStr`.](https://github.com/rust-lang/rust/pull/126877) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-10) Stabilized APIs -------------------------------------------------------------------------------------- * [`std::thread::Builder::spawn_unchecked`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html#method.spawn_unchecked) * [`std::str::CharIndices::offset`](https://doc.rust-lang.org/nightly/std/str/struct.CharIndices.html#method.offset) * [`std::option::Option::is_none_or`](https://doc.rust-lang.org/nightly/std/option/enum.Option.html#method.is_none_or) * [`[T]::is_sorted`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.is_sorted) * [`[T]::is_sorted_by`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.is_sorted_by) * [`[T]::is_sorted_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.is_sorted_by_key) * [`Iterator::is_sorted`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.is_sorted) * [`Iterator::is_sorted_by`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.is_sorted_by) * [`Iterator::is_sorted_by_key`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.is_sorted_by_key) * [`std::future::Ready::into_inner`](https://doc.rust-lang.org/nightly/std/future/struct.Ready.html#method.into_inner) * [`std::iter::repeat_n`](https://doc.rust-lang.org/nightly/std/iter/fn.repeat_n.html) * [`impl DoubleEndedIterator for Take>`](https://doc.rust-lang.org/nightly/std/iter/struct.Take.html#impl-DoubleEndedIterator-for-Take%3CRepeat%3CT%3E%3E) * [`impl ExactSizeIterator for Take>`](https://doc.rust-lang.org/nightly/std/iter/struct.Take.html#impl-ExactSizeIterator-for-Take%3CRepeat%3CT%3E%3E) * [`impl ExactSizeIterator for Take>`](https://doc.rust-lang.org/nightly/std/iter/struct.Take.html#impl-ExactSizeIterator-for-Take%3CRepeatWith%3CF%3E%3E) * [`impl Default for std::collections::binary_heap::Iter`](https://doc.rust-lang.org/nightly/std/collections/binary_heap/struct.Iter.html#impl-Default-for-Iter%3C'_,+T%3E) * [`impl Default for std::collections::btree_map::RangeMut`](https://doc.rust-lang.org/nightly/std/collections/btree_map/struct.RangeMut.html#impl-Default-for-RangeMut%3C'_,+K,+V%3E) * [`impl Default for std::collections::btree_map::ValuesMut`](https://doc.rust-lang.org/nightly/std/collections/btree_map/struct.ValuesMut.html#impl-Default-for-ValuesMut%3C'_,+K,+V%3E) * [`impl Default for std::collections::vec_deque::Iter`](https://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.Iter.html#impl-Default-for-Iter%3C'_,+T%3E) * [`impl Default for std::collections::vec_deque::IterMut`](https://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.IterMut.html#impl-Default-for-IterMut%3C'_,+T%3E) * [`Rc::new_uninit`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new_uninit) * [`Rc>::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init) * [`Rc<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new_uninit_slice) * [`Rc<[MaybeUninit]>::assume_init`](https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.assume_init-1) * [`Arc::new_uninit`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.new_uninit) * [`Arc>::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init) * [`Arc<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.new_uninit_slice) * [`Arc<[MaybeUninit]>::assume_init`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.assume_init-1) * [`Box::new_uninit`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.new_uninit) * [`Box>::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init) * [`Box<[T]>::new_uninit_slice`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.new_uninit_slice) * [`Box<[MaybeUninit]>::assume_init`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html#method.assume_init-1) * [`core::arch::x86_64::_bextri_u64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bextri_u64.html) * [`core::arch::x86_64::_bextri_u32`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bextri_u32.html) * [`core::arch::x86::_mm_broadcastsi128_si256`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_broadcastsi128_si256.html) * [`core::arch::x86::_mm256_stream_load_si256`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm256_stream_load_si256.html) * [`core::arch::x86::_tzcnt_u16`](https://doc.rust-lang.org/stable/core/arch/x86/fn._tzcnt_u16.html) * [`core::arch::x86::_mm_extracti_si64`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_extracti_si64.html) * [`core::arch::x86::_mm_inserti_si64`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_inserti_si64.html) * [`core::arch::x86::_mm_storeu_si16`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_storeu_si16.html) * [`core::arch::x86::_mm_storeu_si32`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_storeu_si32.html) * [`core::arch::x86::_mm_storeu_si64`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_storeu_si64.html) * [`core::arch::x86::_mm_loadu_si16`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_loadu_si16.html) * [`core::arch::x86::_mm_loadu_si32`](https://doc.rust-lang.org/stable/core/arch/x86/fn._mm_loadu_si32.html) * [`core::arch::wasm32::u8x16_relaxed_swizzle`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u8x16_relaxed_swizzle.html) * [`core::arch::wasm32::i8x16_relaxed_swizzle`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i8x16_relaxed_swizzle.html) * [`core::arch::wasm32::i32x4_relaxed_trunc_f32x4`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_trunc_f32x4.html) * [`core::arch::wasm32::u32x4_relaxed_trunc_f32x4`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_trunc_f32x4.html) * [`core::arch::wasm32::i32x4_relaxed_trunc_f64x2_zero`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_trunc_f64x2_zero.html) * [`core::arch::wasm32::u32x4_relaxed_trunc_f64x2_zero`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_trunc_f64x2_zero.html) * [`core::arch::wasm32::f32x4_relaxed_madd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_madd.html) * [`core::arch::wasm32::f32x4_relaxed_nmadd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_nmadd.html) * [`core::arch::wasm32::f64x2_relaxed_madd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_madd.html) * [`core::arch::wasm32::f64x2_relaxed_nmadd`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_nmadd.html) * [`core::arch::wasm32::i8x16_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i8x16_relaxed_laneselect.html) * [`core::arch::wasm32::u8x16_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u8x16_relaxed_laneselect.html) * [`core::arch::wasm32::i16x8_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i16x8_relaxed_laneselect.html) * [`core::arch::wasm32::u16x8_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u16x8_relaxed_laneselect.html) * [`core::arch::wasm32::i32x4_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_laneselect.html) * [`core::arch::wasm32::u32x4_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_laneselect.html) * [`core::arch::wasm32::i64x2_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i64x2_relaxed_laneselect.html) * [`core::arch::wasm32::u64x2_relaxed_laneselect`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u64x2_relaxed_laneselect.html) * [`core::arch::wasm32::f32x4_relaxed_min`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_min.html) * [`core::arch::wasm32::f32x4_relaxed_max`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f32x4_relaxed_max.html) * [`core::arch::wasm32::f64x2_relaxed_min`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_min.html) * [`core::arch::wasm32::f64x2_relaxed_max`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.f64x2_relaxed_max.html) * [`core::arch::wasm32::i16x8_relaxed_q15mulr`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i16x8_relaxed_q15mulr.html) * [`core::arch::wasm32::u16x8_relaxed_q15mulr`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u16x8_relaxed_q15mulr.html) * [`core::arch::wasm32::i16x8_relaxed_dot_i8x16_i7x16`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i16x8_relaxed_dot_i8x16_i7x16.html) * [`core::arch::wasm32::u16x8_relaxed_dot_i8x16_i7x16`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u16x8_relaxed_dot_i8x16_i7x16.html) * [`core::arch::wasm32::i32x4_relaxed_dot_i8x16_i7x16_add`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.i32x4_relaxed_dot_i8x16_i7x16_add.html) * [`core::arch::wasm32::u32x4_relaxed_dot_i8x16_i7x16_add`](https://doc.rust-lang.org/nightly/core/arch/wasm32/fn.u32x4_relaxed_dot_i8x16_i7x16_add.html) These APIs are now stable in const contexts: * [`std::task::Waker::from_raw`](https://doc.rust-lang.org/nightly/std/task/struct.Waker.html#method.from_raw) * [`std::task::Context::from_waker`](https://doc.rust-lang.org/nightly/std/task/struct.Context.html#method.from_waker) * [`std::task::Context::waker`](https://doc.rust-lang.org/nightly/std/task/struct.Context.html#method.waker) * [`{integer}::from_str_radix`](https://doc.rust-lang.org/nightly/std/primitive.u32.html#method.from_str_radix) * [`std::num::ParseIntError::kind`](https://doc.rust-lang.org/nightly/std/num/struct.ParseIntError.html#method.kind) [§](https://doc.rust-lang.org/stable/releases.html#cargo-10) Cargo ------------------------------------------------------------------ * [feat: Add `info` cargo subcommand](https://github.com/rust-lang/cargo/pull/14141/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-10) Compatibility Notes ---------------------------------------------------------------------------------------------- * We now [disallow setting some built-in cfgs via the command-line](https://github.com/rust-lang/rust/pull/126158) with the newly added [`explicit_builtin_cfgs_in_flags`](https://doc.rust-lang.org/rustc/lints/listing/deny-by-default.html#explicit-builtin-cfgs-in-flags) lint in order to prevent incoherent state, eg. `windows` cfg active but target is Linux based. The appropriate [`rustc` flag](https://doc.rust-lang.org/rustc/command-line-arguments.html) should be used instead. * The standard library has a new implementation of `binary_search` which is significantly improves performance ([#128254](https://github.com/rust-lang/rust/pull/128254) ). However when a sorted slice has multiple values which compare equal, the new implementation may select a different value among the equal ones than the old implementation. * [illumos/Solaris now sets `MSG_NOSIGNAL` when writing to sockets](https://github.com/rust-lang/rust/pull/128259) . This avoids killing the process with SIGPIPE when writing to a closed socket, which matches the existing behavior on other UNIX targets. * [Removes a problematic hack that always passed the –whole-archive linker flag for tests, which may cause linker errors for code accidentally relying on it.](https://github.com/rust-lang/rust/pull/128400) * The WebAssembly target features `multivalue` and `reference-types` are now both enabled by default. These two features both have subtle changes implied for generated WebAssembly binaries. For the `multivalue` feature, WebAssembly target support has changed when upgrading to LLVM 19. Support for generating functions with multiple returns no longer works and `-Ctarget-feature=+multivalue` has a different meaning than it did in LLVM 18 and prior. There is no longer any supported means to generate a module that has a function with multiple returns in WebAssembly from Rust source code. For the `reference-types` feature the encoding of immediates in the `call_indirect`, a commonly used instruction by the WebAssembly backend, has changed. Validators and parsers which don’t understand the `reference-types` proposal will no longer accept modules produced by LLVM due to this change in encoding of immediates. Additionally these features being enabled are encoded in the `target_features` custom section and may affect downstream tooling such as `wasm-opt` consuming the module. Generating a WebAssembly module that disables default features requires `-Zbuild-std` support from Cargo and more information can be found at [rust-lang/rust#128511](https://github.com/rust-lang/rust/pull/128511) . * [Rust now raises unsafety errors for union patterns in parameter-position](https://github.com/rust-lang/rust/pull/130531) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-5) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Update to LLVM 19](https://github.com/rust-lang/rust/pull/127513) [§](https://doc.rust-lang.org/stable/releases.html#version-1810-2024-09-05) Version 1.81.0 (2024-09-05) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-11) Language ------------------------------------------------------------------------ * [Abort on uncaught panics in `extern "C"` functions.](https://github.com/rust-lang/rust/pull/116088/) * [Fix ambiguous cases of multiple `&` in elided self lifetimes.](https://github.com/rust-lang/rust/pull/117967/) * [Stabilize `#[expect]` for lints (RFC 2383),](https://github.com/rust-lang/rust/pull/120924/) like `#[allow]` with a warning if the lint is _not_ fulfilled. * [Change method resolution to constrain hidden types instead of rejecting method candidates.](https://github.com/rust-lang/rust/pull/123962/) * [Bump `elided_lifetimes_in_associated_constant` to deny.](https://github.com/rust-lang/rust/pull/124211/) * [`offset_from`: always allow pointers to point to the same address.](https://github.com/rust-lang/rust/pull/124921/) * [Allow constraining opaque types during subtyping in the trait system.](https://github.com/rust-lang/rust/pull/125447/) * [Allow constraining opaque types during various unsizing casts.](https://github.com/rust-lang/rust/pull/125610/) * [Deny keyword lifetimes pre-expansion.](https://github.com/rust-lang/rust/pull/126762/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-11) Compiler ------------------------------------------------------------------------ * [Make casts of pointers to trait objects stricter.](https://github.com/rust-lang/rust/pull/120248/) * [Check alias args for well-formedness even if they have escaping bound vars.](https://github.com/rust-lang/rust/pull/123737/) * [Deprecate no-op codegen option `-Cinline-threshold=...`.](https://github.com/rust-lang/rust/pull/124712/) * [Re-implement a type-size based limit.](https://github.com/rust-lang/rust/pull/125507/) * [Properly account for alignment in `transmute` size checks.](https://github.com/rust-lang/rust/pull/125740/) * [Remove the `box_pointers` lint.](https://github.com/rust-lang/rust/pull/126018/) * [Ensure the interpreter checks bool/char for validity when they are used in a cast.](https://github.com/rust-lang/rust/pull/126265/) * [Improve coverage instrumentation for functions containing nested items.](https://github.com/rust-lang/rust/pull/127199/) * Target changes: * [Add Tier 3 `no_std` Xtensa targets:](https://github.com/rust-lang/rust/pull/125141/) `xtensa-esp32-none-elf`, `xtensa-esp32s2-none-elf`, `xtensa-esp32s3-none-elf` * [Add Tier 3 `std` Xtensa targets:](https://github.com/rust-lang/rust/pull/126380/) `xtensa-esp32-espidf`, `xtensa-esp32s2-espidf`, `xtensa-esp32s3-espidf` * [Add Tier 3 i686 Redox OS target:](https://github.com/rust-lang/rust/pull/126192/) `i686-unknown-redox` * [Promote `arm64ec-pc-windows-msvc` to Tier 2.](https://github.com/rust-lang/rust/pull/126039/) * [Promote `loongarch64-unknown-linux-musl` to Tier 2 with host tools.](https://github.com/rust-lang/rust/pull/126298/) * [Enable full tools and profiler for LoongArch Linux targets.](https://github.com/rust-lang/rust/pull/127078/) * [Unconditionally warn on usage of `wasm32-wasi`.](https://github.com/rust-lang/rust/pull/126662/) (see compatibility note below) * Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-11) Libraries -------------------------------------------------------------------------- * [Split core’s `PanicInfo` and std’s `PanicInfo`.](https://github.com/rust-lang/rust/pull/115974/) (see compatibility note below) * [Generalize `{Rc,Arc}::make_mut()` to unsized types.](https://github.com/rust-lang/rust/pull/116113/) * [Replace sort implementations with stable `driftsort` and unstable `ipnsort`.](https://github.com/rust-lang/rust/pull/124032/) All `slice::sort*` and `slice::select_nth*` methods are expected to see significant performance improvements. See the [research project](https://github.com/Voultapher/sort-research-rs) for more details. * [Document behavior of `create_dir_all` with respect to empty paths.](https://github.com/rust-lang/rust/pull/125112/) * [Fix interleaved output in the default panic hook when multiple threads panic simultaneously.](https://github.com/rust-lang/rust/pull/127397/) * Fix `Command`’s batch files argument escaping not working when file name has trailing whitespace or periods (CVE-2024-43402). [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-11) Stabilized APIs -------------------------------------------------------------------------------------- * [`core::error`](https://doc.rust-lang.org/stable/core/error/index.html) * [`hint::assert_unchecked`](https://doc.rust-lang.org/stable/core/hint/fn.assert_unchecked.html) * [`fs::exists`](https://doc.rust-lang.org/stable/std/fs/fn.exists.html) * [`AtomicBool::fetch_not`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicBool.html#method.fetch_not) * [`Duration::abs_diff`](https://doc.rust-lang.org/stable/core/time/struct.Duration.html#method.abs_diff) * [`IoSlice::advance`](https://doc.rust-lang.org/stable/std/io/struct.IoSlice.html#method.advance) * [`IoSlice::advance_slices`](https://doc.rust-lang.org/stable/std/io/struct.IoSlice.html#method.advance_slices) * [`IoSliceMut::advance`](https://doc.rust-lang.org/stable/std/io/struct.IoSliceMut.html#method.advance) * [`IoSliceMut::advance_slices`](https://doc.rust-lang.org/stable/std/io/struct.IoSliceMut.html#method.advance_slices) * [`PanicHookInfo`](https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html) * [`PanicInfo::message`](https://doc.rust-lang.org/stable/core/panic/struct.PanicInfo.html#method.message) * [`PanicMessage`](https://doc.rust-lang.org/stable/core/panic/struct.PanicMessage.html) These APIs are now stable in const contexts: * [`char::from_u32_unchecked`](https://doc.rust-lang.org/stable/core/char/fn.from_u32_unchecked.html) (function) * [`char::from_u32_unchecked`](https://doc.rust-lang.org/stable/core/primitive.char.html#method.from_u32_unchecked) (method) * [`CStr::count_bytes`](https://doc.rust-lang.org/stable/core/ffi/c_str/struct.CStr.html#method.count_bytes) * [`CStr::from_ptr`](https://doc.rust-lang.org/stable/core/ffi/c_str/struct.CStr.html#method.from_ptr) [§](https://doc.rust-lang.org/stable/releases.html#cargo-11) Cargo ------------------------------------------------------------------ * [Generated `.cargo_vcs_info.json` is always included, even when `--allow-dirty` is passed.](https://github.com/rust-lang/cargo/pull/13960/) * [Disallow `package.license-file` and `package.readme` pointing to non-existent files during packaging.](https://github.com/rust-lang/cargo/pull/13921/) * [Disallow passing `--release`/`--debug` flag along with the `--profile` flag.](https://github.com/rust-lang/cargo/pull/13971/) * [Remove `lib.plugin` key support in `Cargo.toml`. Rust plugin support has been deprecated for four years and was removed in 1.75.0.](https://github.com/rust-lang/cargo/pull/13902/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-11) Compatibility Notes ---------------------------------------------------------------------------------------------- * Usage of the `wasm32-wasi` target will now issue a compiler warning and request users switch to the `wasm32-wasip1` target instead. Both targets are the same, `wasm32-wasi` is only being renamed, and this [change to the WASI target](https://blog.rust-lang.org/2024/04/09/updates-to-rusts-wasi-targets.html) is being done to enable removing `wasm32-wasi` in January 2025. * We have renamed `std::panic::PanicInfo` to `std::panic::PanicHookInfo`. The old name will continue to work as an alias, but will result in a deprecation warning starting in Rust 1.82.0. `core::panic::PanicInfo` will remain unchanged, however, as this is now a _different type_. The reason is that these types have different roles: `std::panic::PanicHookInfo` is the argument to the [panic hook](https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html) in std context (where panics can have an arbitrary payload), while `core::panic::PanicInfo` is the argument to the [`#[panic_handler]`](https://doc.rust-lang.org/nomicon/panic-handler.html) in no\_std context (where panics always carry a formatted _message_). Separating these types allows us to add more useful methods to these types, such as `std::panic::PanicHookInfo::payload_as_str()` and `core::panic::PanicInfo::message()`. * The new sort implementations may panic if a type’s implementation of [`Ord`](https://doc.rust-lang.org/std/cmp/trait.Ord.html) (or the given comparison function) does not implement a [total order](https://en.wikipedia.org/wiki/Total_order) as the trait requires. `Ord`’s supertraits (`PartialOrd`, `Eq`, and `PartialEq`) must also be consistent. The previous implementations would not “notice” any problem, but the new implementations have a good chance of detecting inconsistencies, throwing a panic rather than returning knowingly unsorted data. * [In very rare cases, a change in the internal evaluation order of the trait solver may result in new fatal overflow errors.](https://github.com/rust-lang/rust/pull/126128) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-6) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Add a Rust-for Linux `auto` CI job to check kernel builds.](https://github.com/rust-lang/rust/pull/125209/) [§](https://doc.rust-lang.org/stable/releases.html#version-1801-2024-08-08) Version 1.80.1 (2024-08-08) ======================================================================================================= * [Fix miscompilation in the jump threading MIR optimization when comparing floats](https://github.com/rust-lang/rust/pull/128271) * [Revert changes to the `dead_code` lint from 1.80.0](https://github.com/rust-lang/rust/pull/128618) [§](https://doc.rust-lang.org/stable/releases.html#version-1800-2024-07-25) Version 1.80.0 (2024-07-25) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-12) Language ------------------------------------------------------------------------ * [Document maximum allocation size](https://github.com/rust-lang/rust/pull/116675/) * [Allow zero-byte offsets and ZST read/writes on arbitrary pointers](https://github.com/rust-lang/rust/pull/117329/) * [Support C23’s variadics without a named parameter](https://github.com/rust-lang/rust/pull/124048/) * [Stabilize `exclusive_range_pattern` feature](https://github.com/rust-lang/rust/pull/124459/) * [Guarantee layout and ABI of `Result` in some scenarios](https://github.com/rust-lang/rust/pull/124870) [§](https://doc.rust-lang.org/stable/releases.html#compiler-12) Compiler ------------------------------------------------------------------------ * [Update cc crate to v1.0.97 allowing additional spectre mitigations on MSVC targets](https://github.com/rust-lang/rust/pull/124892/) * [Allow field reordering on types marked `repr(packed(1))`](https://github.com/rust-lang/rust/pull/125360/) * [Add a lint against never type fallback affecting unsafe code](https://github.com/rust-lang/rust/pull/123939/) * [Disallow cast with trailing braced macro in let-else](https://github.com/rust-lang/rust/pull/125049/) * [Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.](https://github.com/rust-lang/rust/pull/125156/) * [self-contained linker: retry linking without `-fuse-ld=lld` on CCs that don’t support it](https://github.com/rust-lang/rust/pull/125417/) * [Do not parse CVarArgs (`...`) as a type in trait bounds](https://github.com/rust-lang/rust/pull/125863/) * Improvements to LLDB formatting [#124458](https://github.com/rust-lang/rust/pull/124458) [#124500](https://github.com/rust-lang/rust/pull/124500) * [For the wasm32-wasip2 target default to PIC and do not use `-fuse-ld=lld`](https://github.com/rust-lang/rust/pull/124858/) * [Add x86\_64-unknown-linux-none as a tier 3 target](https://github.com/rust-lang/rust/pull/125023/) * [Lint on `foo.into_iter()` resolving to `&Box<[T]>: IntoIterator`](https://github.com/rust-lang/rust/pull/124097/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-12) Libraries -------------------------------------------------------------------------- * [Add `size_of` and `size_of_val` and `align_of` and `align_of_val` to the prelude](https://github.com/rust-lang/rust/pull/123168/) * [Abort a process when FD ownership is violated](https://github.com/rust-lang/rust/pull/124210/) * [io::Write::write\_fmt: panic if the formatter fails when the stream does not fail](https://github.com/rust-lang/rust/pull/125012/) * [Panic if `PathBuf::set_extension` would add a path separator](https://github.com/rust-lang/rust/pull/125070/) * [Add assert\_unsafe\_precondition to unchecked\_{add,sub,neg,mul,shl,shr} methods](https://github.com/rust-lang/rust/pull/121571/) * [Update `c_char` on AIX to use the correct type](https://github.com/rust-lang/rust/pull/122986/) * [`offset_of!` no longer returns a temporary](https://github.com/rust-lang/rust/pull/124484/) * [Handle sigma in `str.to_lowercase` correctly](https://github.com/rust-lang/rust/pull/124773/) * [Raise `DEFAULT_MIN_STACK_SIZE` to at least 64KiB](https://github.com/rust-lang/rust/pull/126059/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-12) Stabilized APIs -------------------------------------------------------------------------------------- * [`impl Default for Rc`](https://doc.rust-lang.org/beta/alloc/rc/struct.Rc.html#impl-Default-for-Rc%3CCStr%3E) * [`impl Default for Rc`](https://doc.rust-lang.org/beta/alloc/rc/struct.Rc.html#impl-Default-for-Rc%3Cstr%3E) * [`impl Default for Rc<[T]>`](https://doc.rust-lang.org/beta/alloc/rc/struct.Rc.html#impl-Default-for-Rc%3C%5BT%5D%3E) * [`impl Default for Arc`](https://doc.rust-lang.org/beta/alloc/sync/struct.Arc.html#impl-Default-for-Arc%3Cstr%3E) * [`impl Default for Arc`](https://doc.rust-lang.org/beta/alloc/sync/struct.Arc.html#impl-Default-for-Arc%3CCStr%3E) * [`impl Default for Arc<[T]>`](https://doc.rust-lang.org/beta/alloc/sync/struct.Arc.html#impl-Default-for-Arc%3C%5BT%5D%3E) * [`impl IntoIterator for Box<[T]>`](https://doc.rust-lang.org/beta/alloc/boxed/struct.Box.html#impl-IntoIterator-for-Box%3C%5BI%5D,+A%3E) * [`impl FromIterator for Box`](https://doc.rust-lang.org/beta/alloc/boxed/struct.Box.html#impl-FromIterator%3CString%3E-for-Box%3Cstr%3E) * [`impl FromIterator for Box`](https://doc.rust-lang.org/beta/alloc/boxed/struct.Box.html#impl-FromIterator%3Cchar%3E-for-Box%3Cstr%3E) * [`LazyCell`](https://doc.rust-lang.org/beta/core/cell/struct.LazyCell.html) * [`LazyLock`](https://doc.rust-lang.org/beta/std/sync/struct.LazyLock.html) * [`Duration::div_duration_f32`](https://doc.rust-lang.org/beta/std/time/struct.Duration.html#method.div_duration_f32) * [`Duration::div_duration_f64`](https://doc.rust-lang.org/beta/std/time/struct.Duration.html#method.div_duration_f64) * [`Option::take_if`](https://doc.rust-lang.org/beta/std/option/enum.Option.html#method.take_if) * [`Seek::seek_relative`](https://doc.rust-lang.org/beta/std/io/trait.Seek.html#method.seek_relative) * [`BinaryHeap::as_slice`](https://doc.rust-lang.org/beta/std/collections/struct.BinaryHeap.html#method.as_slice) * [`NonNull::offset`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.offset) * [`NonNull::byte_offset`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_offset) * [`NonNull::add`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.add) * [`NonNull::byte_add`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_add) * [`NonNull::sub`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.sub) * [`NonNull::byte_sub`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_sub) * [`NonNull::offset_from`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.offset_from) * [`NonNull::byte_offset_from`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.byte_offset_from) * [`NonNull::read`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read) * [`NonNull::read_volatile`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read_volatile) * [`NonNull::read_unaligned`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read_unaligned) * [`NonNull::write`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write) * [`NonNull::write_volatile`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write_volatile) * [`NonNull::write_unaligned`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write_unaligned) * [`NonNull::write_bytes`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.write_bytes) * [`NonNull::copy_to`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_to) * [`NonNull::copy_to_nonoverlapping`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_to_nonoverlapping) * [`NonNull::copy_from`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_from) * [`NonNull::copy_from_nonoverlapping`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.copy_from_nonoverlapping) * [`NonNull::replace`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.replace) * [`NonNull::swap`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.swap) * [`NonNull::drop_in_place`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.drop_in_place) * [`NonNull::align_offset`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.align_offset) * [`<[T]>::split_at_checked`](https://doc.rust-lang.org/beta/std/primitive.slice.html#method.split_at_checked) * [`<[T]>::split_at_mut_checked`](https://doc.rust-lang.org/beta/std/primitive.slice.html#method.split_at_mut_checked) * [`str::split_at_checked`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.split_at_checked) * [`str::split_at_mut_checked`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.split_at_mut_checked) * [`str::trim_ascii`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.trim_ascii) * [`str::trim_ascii_start`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.trim_ascii_start) * [`str::trim_ascii_end`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.trim_ascii_end) * [`<[u8]>::trim_ascii`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.trim_ascii) * [`<[u8]>::trim_ascii_start`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.trim_ascii_start) * [`<[u8]>::trim_ascii_end`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.trim_ascii_end) * [`Ipv4Addr::BITS`](https://doc.rust-lang.org/beta/core/net/struct.Ipv4Addr.html#associatedconstant.BITS) * [`Ipv4Addr::to_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv4Addr.html#method.to_bits) * [`Ipv4Addr::from_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv4Addr.html#method.from_bits) * [`Ipv6Addr::BITS`](https://doc.rust-lang.org/beta/core/net/struct.Ipv6Addr.html#associatedconstant.BITS) * [`Ipv6Addr::to_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv6Addr.html#method.to_bits) * [`Ipv6Addr::from_bits`](https://doc.rust-lang.org/beta/core/net/struct.Ipv6Addr.html#method.from_bits) * [`Vec::<[T; N]>::into_flattened`](https://doc.rust-lang.org/beta/alloc/vec/struct.Vec.html#method.into_flattened) * [`<[[T; N]]>::as_flattened`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.as_flattened) * [`<[[T; N]]>::as_flattened_mut`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.as_flattened_mut) These APIs are now stable in const contexts: * [`<[T]>::last_chunk`](https://doc.rust-lang.org/beta/core/primitive.slice.html#method.last_chunk) * [`BinaryHeap::new`](https://doc.rust-lang.org/beta/std/collections/struct.BinaryHeap.html#method.new) [§](https://doc.rust-lang.org/stable/releases.html#cargo-12) Cargo ------------------------------------------------------------------ * [Stabilize `-Zcheck-cfg` as always enabled](https://github.com/rust-lang/cargo/pull/13571/) * [Warn, rather than fail publish, if a target is excluded](https://github.com/rust-lang/cargo/pull/13713/) * [Add special `check-cfg` lint config for the `unexpected_cfgs` lint](https://github.com/rust-lang/cargo/pull/13913/) * [Stabilize `cargo update --precise `](https://github.com/rust-lang/cargo/pull/13974/) * [Don’t change file permissions on `Cargo.toml` when using `cargo add`](https://github.com/rust-lang/cargo/pull/13898/) * [Support using `cargo fix` on IPv6-only networks](https://github.com/rust-lang/cargo/pull/13907/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-9) Rustdoc --------------------------------------------------------------------- * [Allow searching for references](https://github.com/rust-lang/rust/pull/124148/) * [Stabilize `custom_code_classes_in_docs` feature](https://github.com/rust-lang/rust/pull/124577/) * [fix: In cross-crate scenarios show enum variants on type aliases of enums](https://github.com/rust-lang/rust/pull/125300/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-12) Compatibility Notes ---------------------------------------------------------------------------------------------- * [rustfmt estimates line lengths differently when using non-ascii characters](https://github.com/rust-lang/rustfmt/issues/6203) * [Type aliases are now handled correctly in orphan check](https://github.com/rust-lang/rust/pull/117164/) * [Allow instructing rustdoc to read from stdin via `-`](https://github.com/rust-lang/rust/pull/124611/) * [`std::env::{set_var, remove_var}` can no longer be converted to safe function pointers and no longer implement the `Fn` family of traits](https://github.com/rust-lang/rust/pull/124636) * [Warn (or error) when `Self` constructor from outer item is referenced in inner nested item](https://github.com/rust-lang/rust/pull/124187/) * [Turn `indirect_structural_match` and `pointer_structural_match` lints into hard errors](https://github.com/rust-lang/rust/pull/124661/) * [Make `where_clause_object_safety` lint a regular object safety violation](https://github.com/rust-lang/rust/pull/125380/) * [Turn `proc_macro_back_compat` lint into a hard error.](https://github.com/rust-lang/rust/pull/125596/) * [Detect unused structs even when implementing private traits](https://github.com/rust-lang/rust/pull/122382/) * [`std::sync::ReentrantLockGuard` is no longer `Sync` if `T: !Sync`](https://github.com/rust-lang/rust/pull/125527) which means [`std::io::StdoutLock` and `std::io::StderrLock` are no longer Sync](https://github.com/rust-lang/rust/issues/127340) * [Type inference will fail in some cases due to new implementations of `FromIterator for Box`.](https://github.com/rust-lang/rust/pull/99969/) Notably, this breaks versions of the `time` crate before 0.3.35, due to no longer inferring the implementation for `Box<[_]>`. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-7) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * Misc improvements to size of generated html by rustdoc e.g. [#124738](https://github.com/rust-lang/rust/pull/124738/) and [#123734](https://github.com/rust-lang/rust/pull/123734/) * [MSVC targets no longer depend on libc](https://github.com/rust-lang/rust/pull/124050/) [§](https://doc.rust-lang.org/stable/releases.html#version-1790-2024-06-13) Version 1.79.0 (2024-06-13) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-13) Language ------------------------------------------------------------------------ * [Stabilize inline `const {}` expressions.](https://github.com/rust-lang/rust/pull/104087/) * [Prevent opaque types being instantiated twice with different regions within the same function.](https://github.com/rust-lang/rust/pull/116935/) * [Stabilize WebAssembly target features that are in phase 4 and 5.](https://github.com/rust-lang/rust/pull/117457/) * [Add the `redundant_lifetimes` lint to detect lifetimes which are semantically redundant.](https://github.com/rust-lang/rust/pull/118391/) * [Stabilize the `unnameable_types` lint for public types that can’t be named.](https://github.com/rust-lang/rust/pull/120144/) * [Enable debuginfo in macros, and stabilize `-C collapse-macro-debuginfo` and `#[collapse_debuginfo]`.](https://github.com/rust-lang/rust/pull/120845/) * [Propagate temporary lifetime extension into `if` and `match` expressions.](https://github.com/rust-lang/rust/pull/121346/) * [Restrict promotion of `const fn` calls.](https://github.com/rust-lang/rust/pull/121557/) * [Warn against refining impls of crate-private traits with `refining_impl_trait` lint.](https://github.com/rust-lang/rust/pull/121720/) * [Stabilize associated type bounds (RFC 2289).](https://github.com/rust-lang/rust/pull/122055/) * [Stabilize importing `main` from other modules or crates.](https://github.com/rust-lang/rust/pull/122060/) * [Check return types of function types for well-formedness](https://github.com/rust-lang/rust/pull/115538) * [Rework `impl Trait` lifetime inference](https://github.com/rust-lang/rust/pull/116891/) * [Change inductive trait solver cycles to be ambiguous](https://github.com/rust-lang/rust/pull/122791) [§](https://doc.rust-lang.org/stable/releases.html#compiler-13) Compiler ------------------------------------------------------------------------ * [Define `-C strip` to only affect binaries, not artifacts like `.pdb`.](https://github.com/rust-lang/rust/pull/115120/) * [Stabilize `-Crelro-level` for controlling runtime link hardening.](https://github.com/rust-lang/rust/pull/121694/) * [Stabilize checking of `cfg` names and values at compile-time with `--check-cfg`.](https://github.com/rust-lang/rust/pull/123501/) _Note that this only stabilizes the compiler part, the Cargo part is still unstable in this release._ * [Add `aarch64-apple-visionos` and `aarch64-apple-visionos-sim` tier 3 targets.](https://github.com/rust-lang/rust/pull/121419/) * [Add `riscv32ima-unknown-none-elf` tier 3 target.](https://github.com/rust-lang/rust/pull/122696/) * [Promote several Windows targets to tier 2](https://github.com/rust-lang/rust/pull/121712) : `aarch64-pc-windows-gnullvm`, `i686-pc-windows-gnullvm`, and `x86_64-pc-windows-gnullvm`. Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-13) Libraries -------------------------------------------------------------------------- * [Implement `FromIterator` for `(impl Default + Extend, impl Default + Extend)`.](https://github.com/rust-lang/rust/pull/107462/) * [Implement `{Div,Rem}Assign>` on `X`.](https://github.com/rust-lang/rust/pull/121952/) * [Document overrides of `clone_from()` in core/std.](https://github.com/rust-lang/rust/pull/122201/) * [Link MSVC default lib in core.](https://github.com/rust-lang/rust/pull/122268/) * [Caution against using `transmute` between pointers and integers.](https://github.com/rust-lang/rust/pull/122379/) * [Enable frame pointers for the standard library.](https://github.com/rust-lang/rust/pull/122646/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-13) Stabilized APIs -------------------------------------------------------------------------------------- * [`{integer}::unchecked_add`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.unchecked_add) * [`{integer}::unchecked_mul`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.unchecked_mul) * [`{integer}::unchecked_sub`](https://doc.rust-lang.org/stable/core/primitive.i32.html#method.unchecked_sub) * [`<[T]>::split_at_unchecked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_unchecked) * [`<[T]>::split_at_mut_unchecked`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.split_at_mut_unchecked) * [`<[u8]>::utf8_chunks`](https://doc.rust-lang.org/stable/core/primitive.slice.html#method.utf8_chunks) * [`str::Utf8Chunks`](https://doc.rust-lang.org/stable/core/str/struct.Utf8Chunks.html) * [`str::Utf8Chunk`](https://doc.rust-lang.org/stable/core/str/struct.Utf8Chunk.html) * [`<*const T>::is_aligned`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_aligned) * [`<*mut T>::is_aligned`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_aligned-1) * [`NonNull::is_aligned`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.is_aligned) * [`<*const [T]>::len`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.len) * [`<*mut [T]>::len`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.len-1) * [`<*const [T]>::is_empty`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_empty) * [`<*mut [T]>::is_empty`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.is_empty-1) * [`NonNull::<[T]>::is_empty`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.is_empty) * [`CStr::count_bytes`](https://doc.rust-lang.org/stable/core/ffi/c_str/struct.CStr.html#method.count_bytes) * [`io::Error::downcast`](https://doc.rust-lang.org/stable/std/io/struct.Error.html#method.downcast) * [`num::NonZero`](https://doc.rust-lang.org/stable/core/num/struct.NonZero.html) * [`path::absolute`](https://doc.rust-lang.org/stable/std/path/fn.absolute.html) * [`proc_macro::Literal::byte_character`](https://doc.rust-lang.org/stable/proc_macro/struct.Literal.html#method.byte_character) * [`proc_macro::Literal::c_string`](https://doc.rust-lang.org/stable/proc_macro/struct.Literal.html#method.c_string) These APIs are now stable in const contexts: * [`Atomic*::into_inner`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicUsize.html#method.into_inner) * [`io::Cursor::new`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.new) * [`io::Cursor::get_ref`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.get_ref) * [`io::Cursor::position`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#method.position) * [`io::empty`](https://doc.rust-lang.org/stable/std/io/fn.empty.html) * [`io::repeat`](https://doc.rust-lang.org/stable/std/io/fn.repeat.html) * [`io::sink`](https://doc.rust-lang.org/stable/std/io/fn.sink.html) * [`panic::Location::caller`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.caller) * [`panic::Location::file`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.file) * [`panic::Location::line`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.line) * [`panic::Location::column`](https://doc.rust-lang.org/stable/std/panic/struct.Location.html#method.column) [§](https://doc.rust-lang.org/stable/releases.html#cargo-13) Cargo ------------------------------------------------------------------ * [Prevent dashes in `lib.name`, always normalizing to `_`.](https://github.com/rust-lang/cargo/pull/12783/) * [Stabilize MSRV-aware version requirement selection in `cargo add`.](https://github.com/rust-lang/cargo/pull/13608/) * [Switch to using `gitoxide` by default for listing files.](https://github.com/rust-lang/cargo/pull/13696/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-10) Rustdoc ---------------------------------------------------------------------- * [Always display stability version even if it’s the same as the containing item.](https://github.com/rust-lang/rust/pull/118441/) * [Show a single search result for items with multiple paths.](https://github.com/rust-lang/rust/pull/119912/) * [Support typing `/` in docs to begin a search.](https://github.com/rust-lang/rust/pull/123355/) [§](https://doc.rust-lang.org/stable/releases.html#misc) Misc ------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-13) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Update the minimum external LLVM to 17.](https://github.com/rust-lang/rust/pull/122649/) * [`RustcEncodable` and `RustcDecodable` are soft-destabilized, to be removed from the prelude in next edition.](https://github.com/rust-lang/rust/pull/116016/) * [The `wasm_c_abi` future-incompatibility lint will warn about use of the non-spec-compliant C ABI.](https://github.com/rust-lang/rust/pull/117918/) Use `wasm-bindgen v0.2.88` to generate forward-compatible bindings. * [Check return types of function types for well-formedness](https://github.com/rust-lang/rust/pull/115538) [§](https://doc.rust-lang.org/stable/releases.html#version-1780-2024-05-02) Version 1.78.0 (2024-05-02) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-14) Language ------------------------------------------------------------------------ * [Stabilize `#[cfg(target_abi = ...)]`](https://github.com/rust-lang/rust/pull/119590/) * [Stabilize the `#[diagnostic]` namespace and `#[diagnostic::on_unimplemented]` attribute](https://github.com/rust-lang/rust/pull/119888/) * [Make async-fn-in-trait implementable with concrete signatures](https://github.com/rust-lang/rust/pull/120103/) * [Make matching on NaN a hard error, and remove the rest of `illegal_floating_point_literal_pattern`](https://github.com/rust-lang/rust/pull/116284/) * [static mut: allow mutable reference to arbitrary types, not just slices and arrays](https://github.com/rust-lang/rust/pull/117614/) * [Extend `invalid_reference_casting` to include references casting to bigger memory layout](https://github.com/rust-lang/rust/pull/118983/) * [Add `non_contiguous_range_endpoints` lint for singleton gaps after exclusive ranges](https://github.com/rust-lang/rust/pull/118879/) * [Add `wasm_c_abi` lint for use of older wasm-bindgen versions](https://github.com/rust-lang/rust/pull/117918/) This lint currently only works when using Cargo. * [Update `indirect_structural_match` and `pointer_structural_match` lints to match RFC](https://github.com/rust-lang/rust/pull/120423/) * [Make non-`PartialEq`\-typed consts as patterns a hard error](https://github.com/rust-lang/rust/pull/120805/) * [Split `refining_impl_trait` lint into `_reachable`, `_internal` variants](https://github.com/rust-lang/rust/pull/121720/) * [Remove unnecessary type inference when using associated types inside of higher ranked `where`\-bounds](https://github.com/rust-lang/rust/pull/119849) * [Weaken eager detection of cyclic types during type inference](https://github.com/rust-lang/rust/pull/119989) * [`trait Trait: Auto {}`: allow upcasting from `dyn Trait` to `dyn Trait + Auto`](https://github.com/rust-lang/rust/pull/119338) [§](https://doc.rust-lang.org/stable/releases.html#compiler-14) Compiler ------------------------------------------------------------------------ * [Made `INVALID_DOC_ATTRIBUTES` lint deny by default](https://github.com/rust-lang/rust/pull/111505/) * [Increase accuracy of redundant `use` checking](https://github.com/rust-lang/rust/pull/117772/) * [Suggest moving definition if non-found macro\_rules! is defined later](https://github.com/rust-lang/rust/pull/121130/) * [Lower transmutes from int to pointer type as gep on null](https://github.com/rust-lang/rust/pull/121282/) Target changes: * [Windows tier 1 targets now require at least Windows 10](https://github.com/rust-lang/rust/pull/115141/) * [Enable CMPXCHG16B, SSE3, SAHF/LAHF and 128-bit Atomics in tier 1 Windows](https://github.com/rust-lang/rust/pull/120820/) * [Add `wasm32-wasip1` tier 2 (without host tools) target](https://github.com/rust-lang/rust/pull/120468/) * [Add `wasm32-wasip2` tier 3 target](https://github.com/rust-lang/rust/pull/119616/) * [Rename `wasm32-wasi-preview1-threads` to `wasm32-wasip1-threads`](https://github.com/rust-lang/rust/pull/122170/) * [Add `arm64ec-pc-windows-msvc` tier 3 target](https://github.com/rust-lang/rust/pull/119199/) * [Add `armv8r-none-eabihf` tier 3 target for the Cortex-R52](https://github.com/rust-lang/rust/pull/110482/) * [Add `loongarch64-unknown-linux-musl` tier 3 target](https://github.com/rust-lang/rust/pull/121832/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-14) Libraries -------------------------------------------------------------------------- * [Bump Unicode to version 15.1.0, regenerate tables](https://github.com/rust-lang/rust/pull/120777/) * [Make align\_offset, align\_to well-behaved in all cases](https://github.com/rust-lang/rust/pull/121201/) * [PartialEq, PartialOrd: document expectations for transitive chains](https://github.com/rust-lang/rust/pull/115386/) * [Optimize away poison guards when std is built with panic=abort](https://github.com/rust-lang/rust/pull/100603/) * [Replace pthread `RwLock` with custom implementation](https://github.com/rust-lang/rust/pull/110211/) * [Implement unwind safety for Condvar on all platforms](https://github.com/rust-lang/rust/pull/121768/) * [Add ASCII fast-path for `char::is_grapheme_extended`](https://github.com/rust-lang/rust/pull/121138/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-14) Stabilized APIs -------------------------------------------------------------------------------------- * [`impl Read for &Stdin`](https://doc.rust-lang.org/stable/std/io/struct.Stdin.html#impl-Read-for-%26Stdin) * [Accept non `'static` lifetimes for several `std::error::Error` related implementations](https://github.com/rust-lang/rust/pull/113833/) * [Make `impl` impl take `?Sized`](https://github.com/rust-lang/rust/pull/114655/) * [`impl From for io::Error`](https://doc.rust-lang.org/stable/std/io/struct.Error.html#impl-From%3CTryReserveError%3E-for-Error) These APIs are now stable in const contexts: * [`Barrier::new()`](https://doc.rust-lang.org/stable/std/sync/struct.Barrier.html#method.new) [§](https://doc.rust-lang.org/stable/releases.html#cargo-14) Cargo ------------------------------------------------------------------ * [Stabilize lockfile v4](https://github.com/rust-lang/cargo/pull/12852/) * [Respect `rust-version` when generating lockfile](https://github.com/rust-lang/cargo/pull/12861/) * [Control `--charset` via auto-detecting config value](https://github.com/rust-lang/cargo/pull/13337/) * [Support `target..rustdocflags` officially](https://github.com/rust-lang/cargo/pull/13197/) * [Stabilize global cache data tracking](https://github.com/rust-lang/cargo/pull/13492/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-14) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Many unsafe precondition checks now run for user code with debug assertions enabled](https://github.com/rust-lang/rust/pull/120594/) This change helps users catch undefined behavior in their code, though the details of how much is checked are generally not stable. * [riscv only supports split\_debuginfo=off for now](https://github.com/rust-lang/rust/pull/120518/) * [Consistently check bounds on hidden types of `impl Trait`](https://github.com/rust-lang/rust/pull/121679) * [Change equality of higher ranked types to not rely on subtyping](https://github.com/rust-lang/rust/pull/118247) * [When called, additionally check bounds on normalized function return type](https://github.com/rust-lang/rust/pull/118882) * [Expand coverage for `arithmetic_overflow` lint](https://github.com/rust-lang/rust/pull/119432/) * [Fix detection of potential interior mutability in `const` initializers](https://github.com/rust-lang/rust/issues/121250) This code was accidentally accepted. The fix can break generic code that borrows a value of unknown type, as there is currently no way to declare “this type has no interior mutability”. In the future, stabilizing the [`Freeze` trait](https://github.com/rust-lang/rust/issues/121675) will allow proper support for such code. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-8) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Update to LLVM 18](https://github.com/rust-lang/rust/pull/120055/) * [Build `rustc` with 1CGU on `x86_64-pc-windows-msvc`](https://github.com/rust-lang/rust/pull/112267/) * [Build `rustc` with 1CGU on `x86_64-apple-darwin`](https://github.com/rust-lang/rust/pull/112268/) * [Introduce `run-make` V2 infrastructure, a `run_make_support` library and port over 2 tests as example](https://github.com/rust-lang/rust/pull/113026/) * [Windows: Implement condvar, mutex and rwlock using futex](https://github.com/rust-lang/rust/pull/121956/) [§](https://doc.rust-lang.org/stable/releases.html#version-1772-2024-04-09) Version 1.77.2 (2024-04-09) ======================================================================================================= * [CVE-2024-24576: fix escaping of Windows batch file arguments in `std::process::Command`](https://blog.rust-lang.org/2024/04/09/cve-2024-24576.html) [§](https://doc.rust-lang.org/stable/releases.html#version-1771-2024-03-28) Version 1.77.1 (2024-03-28) ======================================================================================================= * [Revert stripping debuginfo by default for Windows](https://github.com/rust-lang/cargo/pull/13654) This fixes a regression in 1.77 by reverting to the previous default. Platforms other than Windows are not affected. * Internal: [Fix heading anchor rendering in doc pages](https://github.com/rust-lang/rust/pull/122693) [§](https://doc.rust-lang.org/stable/releases.html#version-1770-2024-03-21) Version 1.77.0 (2024-03-21) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-15) Language ------------------------------------------------------------------------ * [Reveal opaque types within the defining body for exhaustiveness checking.](https://github.com/rust-lang/rust/pull/116821/) * [Stabilize C-string literals.](https://github.com/rust-lang/rust/pull/117472/) * [Stabilize THIR unsafeck.](https://github.com/rust-lang/rust/pull/117673/) * [Add lint `static_mut_refs` to warn on references to mutable statics.](https://github.com/rust-lang/rust/pull/117556/) * [Support async recursive calls (as long as they have indirection).](https://github.com/rust-lang/rust/pull/117703/) * [Undeprecate lint `unstable_features` and make use of it in the compiler.](https://github.com/rust-lang/rust/pull/118639/) * [Make inductive cycles in coherence ambiguous always.](https://github.com/rust-lang/rust/pull/118649/) * [Get rid of type-driven traversal in const-eval interning](https://github.com/rust-lang/rust/pull/119044/) , only as a [future compatibility lint](https://github.com/rust-lang/rust/pull/122204) for now. * [Deny braced macro invocations in let-else.](https://github.com/rust-lang/rust/pull/119062/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-15) Compiler ------------------------------------------------------------------------ * [Include lint `soft_unstable` in future breakage reports.](https://github.com/rust-lang/rust/pull/116274/) * [Make `i128` and `u128` 16-byte aligned on x86-based targets.](https://github.com/rust-lang/rust/pull/116672/) * [Use `--verbose` in diagnostic output.](https://github.com/rust-lang/rust/pull/119129/) * [Improve spacing between printed tokens.](https://github.com/rust-lang/rust/pull/120227/) * [Merge the `unused_tuple_struct_fields` lint into `dead_code`.](https://github.com/rust-lang/rust/pull/118297/) * [Error on incorrect implied bounds in well-formedness check](https://github.com/rust-lang/rust/pull/118553/) , with a temporary exception for Bevy. * [Fix coverage instrumentation/reports for non-ASCII source code.](https://github.com/rust-lang/rust/pull/119033/) * [Fix `fn`/`const` items implied bounds and well-formedness check.](https://github.com/rust-lang/rust/pull/120019/) * [Promote `riscv32{im|imafc}-unknown-none-elf` targets to tier 2.](https://github.com/rust-lang/rust/pull/118704/) * Add several new tier 3 targets: * [`aarch64-unknown-illumos`](https://github.com/rust-lang/rust/pull/112936/) * [`hexagon-unknown-none-elf`](https://github.com/rust-lang/rust/pull/117601/) * [`riscv32imafc-esp-espidf`](https://github.com/rust-lang/rust/pull/119738/) * [`riscv32im-risc0-zkvm-elf`](https://github.com/rust-lang/rust/pull/117958/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-15) Libraries -------------------------------------------------------------------------- * [Implement `From<&[T; N]>` for `Cow<[T]>`.](https://github.com/rust-lang/rust/pull/113489/) * [Remove special-case handling of `vec.split_off(0)`.](https://github.com/rust-lang/rust/pull/119917/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-15) Stabilized APIs -------------------------------------------------------------------------------------- * [`array::each_ref`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_ref) * [`array::each_mut`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.each_mut) * [`core::net`](https://doc.rust-lang.org/stable/core/net/index.html) * [`f32::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.round_ties_even) * [`f64::round_ties_even`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.round_ties_even) * [`mem::offset_of!`](https://doc.rust-lang.org/stable/std/mem/macro.offset_of.html) * [`slice::first_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.first_chunk) * [`slice::first_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.first_chunk_mut) * [`slice::split_first_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first_chunk) * [`slice::split_first_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first_chunk_mut) * [`slice::last_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.last_chunk) * [`slice::last_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.last_chunk_mut) * [`slice::split_last_chunk`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last_chunk) * [`slice::split_last_chunk_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last_chunk_mut) * [`slice::chunk_by`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.chunk_by) * [`slice::chunk_by_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.chunk_by_mut) * [`Bound::map`](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html#method.map) * [`File::create_new`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.create_new) * [`Mutex::clear_poison`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html#method.clear_poison) * [`RwLock::clear_poison`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html#method.clear_poison) [§](https://doc.rust-lang.org/stable/releases.html#cargo-15) Cargo ------------------------------------------------------------------ * [Extend the build directive syntax with `cargo::`.](https://github.com/rust-lang/cargo/pull/12201/) * [Stabilize metadata `id` format as `PackageIDSpec`.](https://github.com/rust-lang/cargo/pull/12914/) * [Pull out `cargo-util-schemas` as a crate.](https://github.com/rust-lang/cargo/pull/13178/) * [Strip all debuginfo when debuginfo is not requested.](https://github.com/rust-lang/cargo/pull/13257/) * [Inherit jobserver from env for all kinds of runners.](https://github.com/rust-lang/cargo/pull/12776/) * [Deprecate rustc plugin support in cargo.](https://github.com/rust-lang/cargo/pull/13248/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-11) Rustdoc ---------------------------------------------------------------------- * [Allows links in markdown headings.](https://github.com/rust-lang/rust/pull/117662/) * [Search for tuples and unit by type with `()`.](https://github.com/rust-lang/rust/pull/118194/) * [Clean up the source sidebar’s hide button.](https://github.com/rust-lang/rust/pull/119066/) * [Prevent JS injection from `localStorage`.](https://github.com/rust-lang/rust/pull/120250/) [§](https://doc.rust-lang.org/stable/releases.html#misc-1) Misc --------------------------------------------------------------- * [Recommend version-sorting for all sorting in style guide.](https://github.com/rust-lang/rust/pull/115046/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-9) Internal Changes --------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Add more weirdness to `weird-exprs.rs`.](https://github.com/rust-lang/rust/pull/119028/) [§](https://doc.rust-lang.org/stable/releases.html#version-1760-2024-02-08) Version 1.76.0 (2024-02-08) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-16) Language ------------------------------------------------------------------------ * [Document Rust ABI compatibility between various types](https://github.com/rust-lang/rust/pull/115476/) * [Also: guarantee that char and u32 are ABI-compatible](https://github.com/rust-lang/rust/pull/118032/) * [Add lint `ambiguous_wide_pointer_comparisons` that supersedes `clippy::vtable_address_comparisons`](https://github.com/rust-lang/rust/pull/117758) [§](https://doc.rust-lang.org/stable/releases.html#compiler-16) Compiler ------------------------------------------------------------------------ * [Lint pinned `#[must_use]` pointers (in particular, `Box` where `T` is `#[must_use]`) in `unused_must_use`.](https://github.com/rust-lang/rust/pull/118054/) * [Soundness fix: fix computing the offset of an unsized field in a packed struct](https://github.com/rust-lang/rust/pull/118540/) * [Soundness fix: fix dynamic size/align computation logic for packed types with dyn Trait tail](https://github.com/rust-lang/rust/pull/118538/) * [Add `$message_type` field to distinguish json diagnostic outputs](https://github.com/rust-lang/rust/pull/115691/) * [Enable Rust to use the EHCont security feature of Windows](https://github.com/rust-lang/rust/pull/118013/) * [Add tier 3 {x86\_64,i686}-win7-windows-msvc targets](https://github.com/rust-lang/rust/pull/118150/) * [Add tier 3 aarch64-apple-watchos target](https://github.com/rust-lang/rust/pull/119074/) * [Add tier 3 arm64e-apple-ios & arm64e-apple-darwin targets](https://github.com/rust-lang/rust/pull/115526/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-16) Libraries -------------------------------------------------------------------------- * [Add a column number to `dbg!()`](https://github.com/rust-lang/rust/pull/114962/) * [Add `std::hash::{DefaultHasher, RandomState}` exports](https://github.com/rust-lang/rust/pull/115694/) * [Fix rounding issue with exponents in fmt](https://github.com/rust-lang/rust/pull/116301/) * [Add T: ?Sized to `RwLockReadGuard` and `RwLockWriteGuard`’s Debug impls.](https://github.com/rust-lang/rust/pull/117138/) * [Windows: Allow `File::create` to work on hidden files](https://github.com/rust-lang/rust/pull/116438/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-16) Stabilized APIs -------------------------------------------------------------------------------------- * [`Arc::unwrap_or_clone`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.unwrap_or_clone) * [`Rc::unwrap_or_clone`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.unwrap_or_clone) * [`Result::inspect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect) * [`Result::inspect_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect_err) * [`Option::inspect`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.inspect) * [`type_name_of_val`](https://doc.rust-lang.org/stable/std/any/fn.type_name_of_val.html) * [`std::hash::{DefaultHasher, RandomState}`](https://doc.rust-lang.org/stable/std/hash/index.html#structs) These were previously available only through `std::collections::hash_map`. * [`ptr::{from_ref, from_mut}`](https://doc.rust-lang.org/stable/std/ptr/fn.from_ref.html) * [`ptr::addr_eq`](https://doc.rust-lang.org/stable/std/ptr/fn.addr_eq.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-16) Cargo ------------------------------------------------------------------ See [Cargo release notes](https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-176-2024-02-08) . [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-12) Rustdoc ---------------------------------------------------------------------- * [Don’t merge cfg and doc(cfg) attributes for re-exports](https://github.com/rust-lang/rust/pull/113091/) * [rustdoc: allow resizing the sidebar / hiding the top bar](https://github.com/rust-lang/rust/pull/115660/) * [rustdoc-search: add support for traits and associated types](https://github.com/rust-lang/rust/pull/116085/) * [rustdoc: Add highlighting for comments in items declaration](https://github.com/rust-lang/rust/pull/117869/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-15) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Add allow-by-default lint for unit bindings](https://github.com/rust-lang/rust/pull/112380/) This is expected to be upgraded to a warning by default in a future Rust release. Some macros emit bindings with type `()` with user-provided spans, which means that this lint will warn for user code. * [Remove x86\_64-sun-solaris target.](https://github.com/rust-lang/rust/pull/118091/) * [Remove asmjs-unknown-emscripten target](https://github.com/rust-lang/rust/pull/117338/) * [Report errors in jobserver inherited through environment variables](https://github.com/rust-lang/rust/pull/113730/) This [may warn](https://github.com/rust-lang/rust/issues/120515) on benign problems too. * [Update the minimum external LLVM to 16.](https://github.com/rust-lang/rust/pull/117947/) * [Improve `print_tts`](https://github.com/rust-lang/rust/pull/114571/) This change can break some naive manual parsing of token trees in proc macro code which expect a particular structure after `.to_string()`, rather than just arbitrary Rust code. * [Make `IMPLIED_BOUNDS_ENTAILMENT` into a hard error from a lint](https://github.com/rust-lang/rust/pull/117984/) * [Vec’s allocation behavior was changed when collecting some iterators](https://github.com/rust-lang/rust/pull/110353) Allocation behavior is currently not specified, nevertheless changes can be surprising. See [`impl FromIterator for Vec`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#impl-FromIterator%3CT%3E-for-Vec%3CT%3E) for more details. * [Properly reject `default` on free const items](https://github.com/rust-lang/rust/pull/117818/) [§](https://doc.rust-lang.org/stable/releases.html#version-1750-2023-12-28) Version 1.75.0 (2023-12-28) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-17) Language ------------------------------------------------------------------------ * [Stabilize `async fn` and return-position `impl Trait` in traits.](https://github.com/rust-lang/rust/pull/115822/) * [Allow function pointer signatures containing `&mut T` in `const` contexts.](https://github.com/rust-lang/rust/pull/116015/) * [Match `usize`/`isize` exhaustively with half-open ranges.](https://github.com/rust-lang/rust/pull/116692/) * [Guarantee that `char` has the same size and alignment as `u32`.](https://github.com/rust-lang/rust/pull/116894/) * [Document that the null pointer has the 0 address.](https://github.com/rust-lang/rust/pull/116988/) * [Allow partially moved values in `match`.](https://github.com/rust-lang/rust/pull/103208/) * [Add notes about non-compliant FP behavior on 32bit x86 targets.](https://github.com/rust-lang/rust/pull/113053/) * [Stabilize ratified RISC-V target features.](https://github.com/rust-lang/rust/pull/116485/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-17) Compiler ------------------------------------------------------------------------ * [Rework negative coherence to properly consider impls that only partly overlap.](https://github.com/rust-lang/rust/pull/112875/) * [Bump `COINDUCTIVE_OVERLAP_IN_COHERENCE` to deny, and warn in dependencies.](https://github.com/rust-lang/rust/pull/116493/) * [Consider alias bounds when computing liveness in NLL.](https://github.com/rust-lang/rust/pull/116733/) * [Add the V (vector) extension to the `riscv64-linux-android` target spec.](https://github.com/rust-lang/rust/pull/116618/) * [Automatically enable cross-crate inlining for small functions](https://github.com/rust-lang/rust/pull/116505) * Add several new tier 3 targets: * [`csky-unknown-linux-gnuabiv2hf`](https://github.com/rust-lang/rust/pull/117049/) * [`i586-unknown-netbsd`](https://github.com/rust-lang/rust/pull/117170/) * [`mipsel-unknown-netbsd`](https://github.com/rust-lang/rust/pull/117356/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-17) Libraries -------------------------------------------------------------------------- * [Override `Waker::clone_from` to avoid cloning `Waker`s unnecessarily.](https://github.com/rust-lang/rust/pull/96979/) * [Implement `BufRead` for `VecDeque`.](https://github.com/rust-lang/rust/pull/110604/) * [Implement `FusedIterator` for `DecodeUtf16` when the inner iterator does.](https://github.com/rust-lang/rust/pull/110729/) * [Implement `Not, Bit{And,Or}{,Assign}` for IP addresses.](https://github.com/rust-lang/rust/pull/113747/) * [Implement `Default` for `ExitCode`.](https://github.com/rust-lang/rust/pull/114589/) * [Guarantee representation of None in NPO](https://github.com/rust-lang/rust/pull/115333/) * [Document when atomic loads are guaranteed read-only.](https://github.com/rust-lang/rust/pull/115577/) * [Broaden the consequences of recursive TLS initialization.](https://github.com/rust-lang/rust/pull/116172/) * [Windows: Support sub-millisecond sleep.](https://github.com/rust-lang/rust/pull/116461/) * [Fix generic bound of `str::SplitInclusive`’s `DoubleEndedIterator` impl](https://github.com/rust-lang/rust/pull/100806/) * [Fix exit status / wait status on non-Unix `cfg(unix)` platforms.](https://github.com/rust-lang/rust/pull/115108/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-17) Stabilized APIs -------------------------------------------------------------------------------------- * [`Atomic*::from_ptr`](https://doc.rust-lang.org/stable/core/sync/atomic/struct.AtomicUsize.html#method.from_ptr) * [`FileTimes`](https://doc.rust-lang.org/stable/std/fs/struct.FileTimes.html) * [`FileTimesExt`](https://doc.rust-lang.org/stable/std/os/windows/fs/trait.FileTimesExt.html) * [`File::set_modified`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.set_modified) * [`File::set_times`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.set_times) * [`IpAddr::to_canonical`](https://doc.rust-lang.org/stable/core/net/enum.IpAddr.html#method.to_canonical) * [`Ipv6Addr::to_canonical`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.to_canonical) * [`Option::as_slice`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.as_slice) * [`Option::as_mut_slice`](https://doc.rust-lang.org/stable/core/option/enum.Option.html#method.as_mut_slice) * [`pointer::byte_add`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_add) * [`pointer::byte_offset`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_offset) * [`pointer::byte_offset_from`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_offset_from) * [`pointer::byte_sub`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.byte_sub) * [`pointer::wrapping_byte_add`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.wrapping_byte_add) * [`pointer::wrapping_byte_offset`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.wrapping_byte_offset) * [`pointer::wrapping_byte_sub`](https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.wrapping_byte_sub) These APIs are now stable in const contexts: * [`Ipv6Addr::to_ipv4_mapped`](https://doc.rust-lang.org/stable/core/net/struct.Ipv6Addr.html#method.to_ipv4_mapped) * [`MaybeUninit::assume_init_read`](https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#method.assume_init_read) * [`MaybeUninit::zeroed`](https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#method.zeroed) * [`mem::discriminant`](https://doc.rust-lang.org/stable/core/mem/fn.discriminant.html) * [`mem::zeroed`](https://doc.rust-lang.org/stable/core/mem/fn.zeroed.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-17) Cargo ------------------------------------------------------------------ * [Add new packages to `[workspace.members]` automatically.](https://github.com/rust-lang/cargo/pull/12779/) * [Allow version-less `Cargo.toml` manifests.](https://github.com/rust-lang/cargo/pull/12786/) * [Make browser links out of HTML file paths.](https://github.com/rust-lang/cargo/pull/12889) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-13) Rustdoc ---------------------------------------------------------------------- * [Accept less invalid Rust in rustdoc.](https://github.com/rust-lang/rust/pull/117450/) * [Document lack of object safety on affected traits.](https://github.com/rust-lang/rust/pull/113241/) * [Hide `#[repr(transparent)]` if it isn’t part of the public ABI.](https://github.com/rust-lang/rust/pull/115439/) * [Show enum discriminant if it is a C-like variant.](https://github.com/rust-lang/rust/pull/116142/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-16) Compatibility Notes ---------------------------------------------------------------------------------------------- * [FreeBSD targets now require at least version 12.](https://github.com/rust-lang/rust/pull/114521/) * [Formally demote tier 2 MIPS targets to tier 3.](https://github.com/rust-lang/rust/pull/115238/) * [Make misalignment a hard error in `const` contexts.](https://github.com/rust-lang/rust/pull/115524/) * [Fix detecting references to packed unsized fields.](https://github.com/rust-lang/rust/pull/115583/) * [Remove support for compiler plugins.](https://github.com/rust-lang/rust/pull/116412/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-10) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Optimize `librustc_driver.so` with BOLT.](https://github.com/rust-lang/rust/pull/116352/) * [Enable parallel rustc front end in dev and nightly builds.](https://github.com/rust-lang/rust/pull/117435/) * [Distribute `rustc-codegen-cranelift` as rustup component on the nightly channel.](https://github.com/rust-lang/rust/pull/81746/) [§](https://doc.rust-lang.org/stable/releases.html#version-1741-2023-12-07) Version 1.74.1 (2023-12-07) ======================================================================================================= * [Resolved spurious STATUS\_ACCESS\_VIOLATIONs in LLVM](https://github.com/rust-lang/rust/pull/118464) * [Clarify guarantees for std::mem::discriminant](https://github.com/rust-lang/rust/pull/118006) * [Fix some subtyping-related regressions](https://github.com/rust-lang/rust/pull/116415) [§](https://doc.rust-lang.org/stable/releases.html#version-1740-2023-11-16) Version 1.74.0 (2023-11-16) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-18) Language ------------------------------------------------------------------------ * [Codify that `std::mem::Discriminant` does not depend on any lifetimes in T](https://github.com/rust-lang/rust/pull/104299/) * [Replace `private_in_public` lint with `private_interfaces` and `private_bounds` per RFC 2145.](https://github.com/rust-lang/rust/pull/113126/) Read more in [RFC 2145](https://rust-lang.github.io/rfcs/2145-type-privacy.html) . * [Allow explicit `#[repr(Rust)]`](https://github.com/rust-lang/rust/pull/114201/) * [closure field capturing: don’t depend on alignment of packed fields](https://github.com/rust-lang/rust/pull/115315/) * [Enable MIR-based drop-tracking for `async` blocks](https://github.com/rust-lang/rust/pull/107421/) * [Stabilize `impl_trait_projections`](https://github.com/rust-lang/rust/pull/115659) [§](https://doc.rust-lang.org/stable/releases.html#compiler-18) Compiler ------------------------------------------------------------------------ * [stabilize combining +bundle and +whole-archive link modifiers](https://github.com/rust-lang/rust/pull/113301/) * [Stabilize `PATH` option for `--print KIND=PATH`](https://github.com/rust-lang/rust/pull/114183/) * [Enable ASAN/LSAN/TSAN for `*-apple-ios-macabi`](https://github.com/rust-lang/rust/pull/115644/) * [Promote loongarch64-unknown-none\* to Tier 2](https://github.com/rust-lang/rust/pull/115368/) * [Add `i686-pc-windows-gnullvm` as a tier 3 target](https://github.com/rust-lang/rust/pull/115687/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-18) Libraries -------------------------------------------------------------------------- * [Implement `From` for ChildStdin/out/err](https://github.com/rust-lang/rust/pull/98704/) * [Implement `From<{&,&mut} [T; N]>` for `Vec` where `T: Clone`](https://github.com/rust-lang/rust/pull/111278/) * [impl Step for IP addresses](https://github.com/rust-lang/rust/pull/113748/) * [Implement `From<[T; N]>` for `Rc<[T]>` and `Arc<[T]>`](https://github.com/rust-lang/rust/pull/114041/) * [`impl TryFrom for u16`](https://github.com/rust-lang/rust/pull/114065/) * [Stabilize `io_error_other` feature](https://github.com/rust-lang/rust/pull/115453/) * [Stabilize the `Saturating` type](https://github.com/rust-lang/rust/pull/115477/) * [Stabilize const\_transmute\_copy](https://github.com/rust-lang/rust/pull/115520/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-18) Stabilized APIs -------------------------------------------------------------------------------------- * [`core::num::Saturating`](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html) * [`impl From for std::process::Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html#impl-From%3CStdout%3E-for-Stdio) * [`impl From for std::process::Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html#impl-From%3CStderr%3E-for-Stdio) * [`impl From for std::process::Child{Stdin, Stdout, Stderr}`](https://doc.rust-lang.org/stable/std/process/struct.ChildStderr.html#impl-From%3COwnedHandle%3E-for-ChildStderr) * [`impl From for std::process::Child{Stdin, Stdout, Stderr}`](https://doc.rust-lang.org/stable/std/process/struct.ChildStderr.html#impl-From%3COwnedFd%3E-for-ChildStderr) * [`std::ffi::OsString::from_encoded_bytes_unchecked`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.from_encoded_bytes_unchecked) * [`std::ffi::OsString::into_encoded_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.into_encoded_bytes) * [`std::ffi::OsStr::from_encoded_bytes_unchecked`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.from_encoded_bytes_unchecked) * [`std::ffi::OsStr::as_encoded_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.as_encoded_bytes) * [`std::io::Error::other`](https://doc.rust-lang.org/stable/std/io/struct.Error.html#method.other) * [`impl TryFrom for u16`](https://doc.rust-lang.org/stable/std/primitive.u16.html#impl-TryFrom%3Cchar%3E-for-u16) * [`impl From<&[T; N]> for Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#impl-From%3C%26%5BT;+N%5D%3E-for-Vec%3CT,+Global%3E) * [`impl From<&mut [T; N]> for Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#impl-From%3C%26mut+%5BT;+N%5D%3E-for-Vec%3CT,+Global%3E) * [`impl From<[T; N]> for Arc<[T]>`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#impl-From%3C%5BT;+N%5D%3E-for-Arc%3C%5BT%5D,+Global%3E) * [`impl From<[T; N]> for Rc<[T]>`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#impl-From%3C%5BT;+N%5D%3E-for-Rc%3C%5BT%5D,+Global%3E) These APIs are now stable in const contexts: * [`core::mem::transmute_copy`](https://doc.rust-lang.org/beta/std/mem/fn.transmute_copy.html) * [`str::is_ascii`](https://doc.rust-lang.org/beta/std/primitive.str.html#method.is_ascii) * [`[u8]::is_ascii`](https://doc.rust-lang.org/beta/std/primitive.slice.html#method.is_ascii) [§](https://doc.rust-lang.org/stable/releases.html#cargo-18) Cargo ------------------------------------------------------------------ * [In `Cargo.toml`, stabilize `[lints]`](https://github.com/rust-lang/cargo/pull/12648/) * [Stabilize credential-process and registry-auth](https://github.com/rust-lang/cargo/pull/12649/) * [Stabilize `--keep-going` build flag](https://github.com/rust-lang/cargo/pull/12568/) * [Add styling to `--help` output](https://github.com/rust-lang/cargo/pull/12578/) * [For `cargo clean`, add `--dry-run` flag and summary line at the end](https://github.com/rust-lang/cargo/pull/12638) * [For `cargo update`, make `--package` more convenient by being positional](https://github.com/rust-lang/cargo/pull/12545/) * [For `cargo update`, clarify meaning of –aggressive as –recursive](https://github.com/rust-lang/cargo/pull/12544/) * [Add ‘-n’ as an alias for `--dry-run`](https://github.com/rust-lang/cargo/pull/12660/) * [Allow version-prefixes in pkgid’s (e.g. `--package` flags) to resolve ambiguities](https://github.com/rust-lang/cargo/pull/12614/) * [In `.cargo/config.toml`, merge lists in precedence order](https://github.com/rust-lang/cargo/pull/12515/) * [Add support for `target.'cfg(..)'.linker`](https://github.com/rust-lang/cargo/pull/12535/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-14) Rustdoc ---------------------------------------------------------------------- * [Add warning block support in rustdoc](https://github.com/rust-lang/rust/pull/106561/) * [rustdoc-search: add support for type parameters](https://github.com/rust-lang/rust/pull/112725/) * [rustdoc: show inner enum and struct in type definition for concrete type](https://github.com/rust-lang/rust/pull/114855/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-17) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Raise minimum supported Apple OS versions](https://github.com/rust-lang/rust/pull/104385/) * [make Cell::swap panic if the Cells partially overlap](https://github.com/rust-lang/rust/pull/114795/) * [Reject invalid crate names in `--extern`](https://github.com/rust-lang/rust/pull/116001/) * [Don’t resolve generic impls that may be shadowed by dyn built-in impls](https://github.com/rust-lang/rust/pull/114941/) * [The new `impl From<{&,&mut} [T; N]> for Vec` is known to cause some inference failures with overly-generic code.](https://github.com/rust-lang/rust/issues/117054) In those examples using the `tui` crate, the combination of `AsRef<_>` and `Into` leaves the middle type ambiguous, and the new `impl` adds another possibility, so it now requires an explicit type annotation. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-11) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. None this cycle. [§](https://doc.rust-lang.org/stable/releases.html#version-1730-2023-10-05) Version 1.73.0 (2023-10-05) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-19) Language ------------------------------------------------------------------------ * [Uplift `clippy::fn_null_check` lint as `useless_ptr_null_checks`.](https://github.com/rust-lang/rust/pull/111717/) * [Make `noop_method_call` warn by default.](https://github.com/rust-lang/rust/pull/111916/) * [Support interpolated block for `try` and `async` in macros.](https://github.com/rust-lang/rust/pull/112953/) * [Make `unconditional_recursion` lint detect recursive drops.](https://github.com/rust-lang/rust/pull/113902/) * [Future compatibility warning for some impls being incorrectly considered not overlapping.](https://github.com/rust-lang/rust/pull/114023/) * [The `invalid_reference_casting` lint is now **deny-by-default** (instead of allow-by-default)](https://github.com/rust-lang/rust/pull/112431) [§](https://doc.rust-lang.org/stable/releases.html#compiler-19) Compiler ------------------------------------------------------------------------ * [Write version information in a `.comment` section like GCC/Clang.](https://github.com/rust-lang/rust/pull/97550/) * [Add documentation on v0 symbol mangling.](https://github.com/rust-lang/rust/pull/97571/) * [Stabilize `extern "thiscall"` and `"thiscall-unwind"` ABIs.](https://github.com/rust-lang/rust/pull/114562/) * [Only check outlives goals on impl compared to trait.](https://github.com/rust-lang/rust/pull/109356/) * [Infer type in irrefutable slice patterns with fixed length as array.](https://github.com/rust-lang/rust/pull/113199/) * [Discard default auto trait impls if explicit ones exist.](https://github.com/rust-lang/rust/pull/113312/) * Add several new tier 3 targets: * [`aarch64-unknown-teeos`](https://github.com/rust-lang/rust/pull/113480/) * [`csky-unknown-linux-gnuabiv2`](https://github.com/rust-lang/rust/pull/113658/) * [`riscv64-linux-android`](https://github.com/rust-lang/rust/pull/112858/) * [`riscv64gc-unknown-hermit`](https://github.com/rust-lang/rust/pull/114004/) * [`x86_64-unikraft-linux-musl`](https://github.com/rust-lang/rust/pull/113411/) * [`x86_64-unknown-linux-ohos`](https://github.com/rust-lang/rust/pull/113061/) * [Add `wasm32-wasi-preview1-threads` as a tier 2 target.](https://github.com/rust-lang/rust/pull/112922/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-19) Libraries -------------------------------------------------------------------------- * [Add `Read`, `Write` and `Seek` impls for `Arc`.](https://github.com/rust-lang/rust/pull/94748/) * [Merge functionality of `io::Sink` into `io::Empty`.](https://github.com/rust-lang/rust/pull/98154/) * [Implement `RefUnwindSafe` for `Backtrace`](https://github.com/rust-lang/rust/pull/100455/) * [Make `ExitStatus` implement `Default`](https://github.com/rust-lang/rust/pull/106425/) * [`impl SliceIndex for (Bound, Bound)`](https://github.com/rust-lang/rust/pull/111081/) * [Change default panic handler message format.](https://github.com/rust-lang/rust/pull/112849/) * [Cleaner `assert_eq!` & `assert_ne!` panic messages.](https://github.com/rust-lang/rust/pull/111071/) * [Correct the (deprecated) Android `stat` struct definitions.](https://github.com/rust-lang/rust/pull/113130/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-19) Stabilized APIs -------------------------------------------------------------------------------------- * [Unsigned `{integer}::div_ceil`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.div_ceil) * [Unsigned `{integer}::next_multiple_of`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.next_multiple_of) * [Unsigned `{integer}::checked_next_multiple_of`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.checked_next_multiple_of) * [`std::ffi::FromBytesUntilNulError`](https://doc.rust-lang.org/stable/std/ffi/struct.FromBytesUntilNulError.html) * [`std::os::unix::fs::chown`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.chown.html) * [`std::os::unix::fs::fchown`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.fchown.html) * [`std::os::unix::fs::lchown`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.lchown.html) * [`LocalKey::>::get`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.get) * [`LocalKey::>::set`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.set) * [`LocalKey::>::take`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.take) * [`LocalKey::>::replace`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.replace) * [`LocalKey::>::with_borrow`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with_borrow) * [`LocalKey::>::with_borrow_mut`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with_borrow_mut) * [`LocalKey::>::set`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.set-1) * [`LocalKey::>::take`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.take-1) * [`LocalKey::>::replace`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.replace-1) These APIs are now stable in const contexts: * [`rc::Weak::new`](https://doc.rust-lang.org/stable/alloc/rc/struct.Weak.html#method.new) * [`sync::Weak::new`](https://doc.rust-lang.org/stable/alloc/sync/struct.Weak.html#method.new) * [`NonNull::as_ref`](https://doc.rust-lang.org/stable/core/ptr/struct.NonNull.html#method.as_ref) [§](https://doc.rust-lang.org/stable/releases.html#cargo-19) Cargo ------------------------------------------------------------------ * [Bail out an error when using `cargo::` in custom build script.](https://github.com/rust-lang/cargo/pull/12332/) [§](https://doc.rust-lang.org/stable/releases.html#misc-2) Misc --------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-18) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Update the minimum external LLVM to 15.](https://github.com/rust-lang/rust/pull/114148/) * [Check for non-defining uses of return position `impl Trait`.](https://github.com/rust-lang/rust/pull/112842/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-12) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Remove LLVM pointee types, supporting only opaque pointers.](https://github.com/rust-lang/rust/pull/105545/) * [Port PGO/LTO/BOLT optimized build pipeline to Rust.](https://github.com/rust-lang/rust/pull/112235/) * [Replace in-tree `rustc_apfloat` with the new version of the crate.](https://github.com/rust-lang/rust/pull/113843/) * [Update to LLVM 17.](https://github.com/rust-lang/rust/pull/114048/) * [Add `internal_features` lint for internal unstable features.](https://github.com/rust-lang/rust/pull/108955/) * [Mention style for new syntax in tracking issue template.](https://github.com/rust-lang/rust/pull/113586/) [§](https://doc.rust-lang.org/stable/releases.html#version-1721-2023-09-19) Version 1.72.1 (2023-09-19) ======================================================================================================= * [Adjust codegen change to improve LLVM codegen](https://github.com/rust-lang/rust/pull/115236) * [rustdoc: Fix self ty params in objects with lifetimes](https://github.com/rust-lang/rust/pull/115276) * [Fix regression in compile times](https://github.com/rust-lang/rust/pull/114948) * Resolve some ICE regressions in the compiler: * [#115215](https://github.com/rust-lang/rust/pull/115215) * [#115559](https://github.com/rust-lang/rust/pull/115559) [§](https://doc.rust-lang.org/stable/releases.html#version-1720-2023-08-24) Version 1.72.0 (2023-08-24) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-20) Language ------------------------------------------------------------------------ * [Replace const eval limit by a lint and add an exponential backoff warning](https://github.com/rust-lang/rust/pull/103877/) * [expand: Change how `#![cfg(FALSE)]` behaves on crate root](https://github.com/rust-lang/rust/pull/110141/) * [Stabilize inline asm for LoongArch64](https://github.com/rust-lang/rust/pull/111235/) * [Uplift `clippy::undropped_manually_drops` lint](https://github.com/rust-lang/rust/pull/111530/) * [Uplift `clippy::invalid_utf8_in_unchecked` lint](https://github.com/rust-lang/rust/pull/111543/) as `invalid_from_utf8_unchecked` and `invalid_from_utf8` * [Uplift `clippy::cast_ref_to_mut` lint](https://github.com/rust-lang/rust/pull/111567/) as `invalid_reference_casting` * [Uplift `clippy::cmp_nan` lint](https://github.com/rust-lang/rust/pull/111818/) as `invalid_nan_comparisons` * [resolve: Remove artificial import ambiguity errors](https://github.com/rust-lang/rust/pull/112086/) * [Don’t require associated types with Self: Sized bounds in `dyn Trait` objects](https://github.com/rust-lang/rust/pull/112319/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-20) Compiler ------------------------------------------------------------------------ * [Remember names of `cfg`\-ed out items to mention them in diagnostics](https://github.com/rust-lang/rust/pull/109005/) * [Support for native WASM exceptions](https://github.com/rust-lang/rust/pull/111322/) * [Add support for NetBSD/aarch64-be (big-endian arm64).](https://github.com/rust-lang/rust/pull/111326/) * [Write to stdout if `-` is given as output file](https://github.com/rust-lang/rust/pull/111626/) * [Force all native libraries to be statically linked when linking a static binary](https://github.com/rust-lang/rust/pull/111698/) * [Add Tier 3 support for `loongarch64-unknown-none*`](https://github.com/rust-lang/rust/pull/112310/) * [Prevent `.eh_frame` from being emitted for `-C panic=abort`](https://github.com/rust-lang/rust/pull/112403/) * [Support 128-bit enum variant in debuginfo codegen](https://github.com/rust-lang/rust/pull/112474/) * [compiler: update solaris/illumos to enable tsan support.](https://github.com/rust-lang/rust/pull/112039/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-20) Libraries -------------------------------------------------------------------------- * [Document memory orderings of `thread::{park, unpark}`](https://github.com/rust-lang/rust/pull/99587/) * [io: soften ‘at most one write attempt’ requirement in io::Write::write](https://github.com/rust-lang/rust/pull/107200/) * [Specify behavior of HashSet::insert](https://github.com/rust-lang/rust/pull/107619/) * [Relax implicit `T: Sized` bounds on `BufReader`, `BufWriter` and `LineWriter`](https://github.com/rust-lang/rust/pull/111074/) * [Update runtime guarantee for `select_nth_unstable`](https://github.com/rust-lang/rust/pull/111974/) * [Return `Ok` on kill if process has already exited](https://github.com/rust-lang/rust/pull/112594/) * [Implement PartialOrd for `Vec`s over different allocators](https://github.com/rust-lang/rust/pull/112632/) * [Use 128 bits for TypeId hash](https://github.com/rust-lang/rust/pull/109953/) * [Don’t drain-on-drop in DrainFilter impls of various collections.](https://github.com/rust-lang/rust/pull/104455/) * [Make `{Arc,Rc,Weak}::ptr_eq` ignore pointer metadata](https://github.com/rust-lang/rust/pull/106450/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-15) Rustdoc ---------------------------------------------------------------------- * [Allow whitespace as path separator like double colon](https://github.com/rust-lang/rust/pull/108537/) * [Add search result item types after their name](https://github.com/rust-lang/rust/pull/110688/) * [Search for slices and arrays by type with `[]`](https://github.com/rust-lang/rust/pull/111958/) * [Clean up type unification and “unboxing”](https://github.com/rust-lang/rust/pull/112233/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-20) Stabilized APIs -------------------------------------------------------------------------------------- * [`impl Sync for mpsc::Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html#impl-Sync-for-Sender%3CT%3E) * [`impl TryFrom<&OsStr> for &str`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-TryFrom%3C%26'a+OsStr%3E-for-%26'a+str) * [`String::leak`](https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.leak) These APIs are now stable in const contexts: * [`CStr::from_bytes_with_nul`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.from_bytes_with_nul) * [`CStr::to_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.to_bytes) * [`CStr::to_bytes_with_nul`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.to_bytes_with_nul) * [`CStr::to_str`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.to_str) [§](https://doc.rust-lang.org/stable/releases.html#cargo-20) Cargo ------------------------------------------------------------------ * Enable `-Zdoctest-in-workspace` by default. When running each documentation test, the working directory is set to the root directory of the package the test belongs to. [docs](https://doc.rust-lang.org/nightly/cargo/commands/cargo-test.html#working-directory-of-tests) [#12221](https://github.com/rust-lang/cargo/pull/12221) [#12288](https://github.com/rust-lang/cargo/pull/12288) * Add support of the “default” keyword to reset previously set `build.jobs` parallelism back to the default. [#12222](https://github.com/rust-lang/cargo/pull/12222) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-19) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Alter `Display` for `Ipv6Addr` for IPv4-compatible addresses](https://github.com/rust-lang/rust/pull/112606/) * Cargo changed feature name validation check to a hard error. The warning was added in Rust 1.49. These extended characters aren’t allowed on crates.io, so this should only impact users of other registries, or people who don’t publish to a registry. [#12291](https://github.com/rust-lang/cargo/pull/12291) * [Demoted `mips*-unknown-linux-gnu*` targets from host tier 2 to target tier 3 support.](https://github.com/rust-lang/rust/pull/113274) [§](https://doc.rust-lang.org/stable/releases.html#version-1711-2023-08-03) Version 1.71.1 (2023-08-03) ======================================================================================================= * [Fix CVE-2023-38497: Cargo did not respect the umask when extracting dependencies](https://github.com/rust-lang/cargo/security/advisories/GHSA-j3xp-wfr4-hx87) * [Fix bash completion for users of Rustup](https://github.com/rust-lang/rust/pull/113579) * [Do not show `suspicious_double_ref_op` lint when calling `borrow()`](https://github.com/rust-lang/rust/pull/112517) * [Fix ICE: substitute types before checking inlining compatibility](https://github.com/rust-lang/rust/pull/113802) * [Fix ICE: don’t use `can_eq` in `derive(..)` suggestion for missing method](https://github.com/rust-lang/rust/pull/111516) * [Fix building Rust 1.71.0 from the source tarball](https://github.com/rust-lang/rust/issues/113678) [§](https://doc.rust-lang.org/stable/releases.html#version-1710-2023-07-13) Version 1.71.0 (2023-07-13) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-21) Language ------------------------------------------------------------------------ * [Stabilize `raw-dylib`, `link_ordinal`, `import_name_type` and `-Cdlltool`.](https://github.com/rust-lang/rust/pull/109677/) * [Uplift `clippy::{drop,forget}_{ref,copy}` lints.](https://github.com/rust-lang/rust/pull/109732/) * [Type inference is more conservative around constrained vars.](https://github.com/rust-lang/rust/pull/110100/) * [Use fulfillment to check `Drop` impl compatibility](https://github.com/rust-lang/rust/pull/110577/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-21) Compiler ------------------------------------------------------------------------ * [Evaluate place expression in `PlaceMention`](https://github.com/rust-lang/rust/pull/104844/) , making `let _ =` patterns more consistent with respect to the borrow checker. * [Add `--print deployment-target` flag for Apple targets.](https://github.com/rust-lang/rust/pull/105354/) * [Stabilize `extern "C-unwind"` and friends.](https://github.com/rust-lang/rust/pull/106075/) The existing `extern "C"` etc. may change behavior for cross-language unwinding in a future release. * [Update the version of musl used on `*-linux-musl` targets to 1.2.3](https://github.com/rust-lang/rust/pull/107129/) , enabling [time64](https://musl.libc.org/time64.html) on 32-bit systems. * [Stabilize `debugger_visualizer`](https://github.com/rust-lang/rust/pull/108668/) for embedding metadata like Microsoft’s Natvis. * [Enable flatten-format-args by default.](https://github.com/rust-lang/rust/pull/109999/) * [Make `Self` respect tuple constructor privacy.](https://github.com/rust-lang/rust/pull/111245/) * [Improve niche placement by trying two strategies and picking the better result.](https://github.com/rust-lang/rust/pull/108106/) * [Use `apple-m1` as the target CPU for `aarch64-apple-darwin`.](https://github.com/rust-lang/rust/pull/109899/) * [Add Tier 3 support for the `x86_64h-apple-darwin` target.](https://github.com/rust-lang/rust/pull/108795/) * [Promote `loongarch64-unknown-linux-gnu` to Tier 2 with host tools.](https://github.com/rust-lang/rust/pull/110936/) Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-21) Libraries -------------------------------------------------------------------------- * [Rework handling of recursive panics.](https://github.com/rust-lang/rust/pull/110975/) Additional panics are allowed while unwinding, as long as they are caught before escaping a `Drop` implementation, but panicking within a panic hook is now an immediate abort. * [Loosen `From<&[T]> for Box<[T]>` bound to `T: Clone`.](https://github.com/rust-lang/rust/pull/103406/) * [Remove unnecessary `T: Send` bound](https://github.com/rust-lang/rust/pull/111134/) in `Error for mpsc::SendError` and `TrySendError`. * [Fix docs for `alloc::realloc`](https://github.com/rust-lang/rust/pull/108630/) to match `Layout` requirements that the size must not exceed `isize::MAX`. * [Document `const {}` syntax for `std::thread_local`.](https://github.com/rust-lang/rust/pull/110620/) This syntax was stabilized in Rust 1.59, but not previously mentioned in release notes. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-21) Stabilized APIs -------------------------------------------------------------------------------------- * [`CStr::is_empty`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.is_empty) * [`BuildHasher::hash_one`](https://doc.rust-lang.org/stable/std/hash/trait.BuildHasher.html#method.hash_one) * [`NonZeroI*::is_positive`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.is_positive) * [`NonZeroI*::is_negative`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.is_negative) * [`NonZeroI*::checked_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.checked_neg) * [`NonZeroI*::overflowing_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.overflowing_neg) * [`NonZeroI*::saturating_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.saturating_neg) * [`NonZeroI*::wrapping_neg`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#method.wrapping_neg) * [`Neg for NonZeroI*`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#impl-Neg-for-NonZeroI32) * [`Neg for &NonZeroI*`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI32.html#impl-Neg-for-%26NonZeroI32) * [`From<[T; N]> for (T...)`](https://doc.rust-lang.org/stable/std/primitive.array.html#impl-From%3C%5BT;+1%5D%3E-for-(T,)) (array to N-tuple for N in 1..=12) * [`From<(T...)> for [T; N]`](https://doc.rust-lang.org/stable/std/primitive.array.html#impl-From%3C(T,)%3E-for-%5BT;+1%5D) (N-tuple to array for N in 1..=12) * [`windows::io::AsHandle for Box`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html#impl-AsHandle-for-Box%3CT%3E) * [`windows::io::AsHandle for Rc`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html#impl-AsHandle-for-Rc%3CT%3E) * [`windows::io::AsHandle for Arc`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html#impl-AsHandle-for-Arc%3CT%3E) * [`windows::io::AsSocket for Box`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html#impl-AsSocket-for-Box%3CT%3E) * [`windows::io::AsSocket for Rc`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html#impl-AsSocket-for-Rc%3CT%3E) * [`windows::io::AsSocket for Arc`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html#impl-AsSocket-for-Arc%3CT%3E) These APIs are now stable in const contexts: * [`<*const T>::read`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read) * [`<*const T>::read_unaligned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read_unaligned) * [`<*mut T>::read`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read-1) * [`<*mut T>::read_unaligned`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.read_unaligned-1) * [`ptr::read`](https://doc.rust-lang.org/stable/std/ptr/fn.read.html) * [`ptr::read_unaligned`](https://doc.rust-lang.org/stable/std/ptr/fn.read_unaligned.html) * [`<[T]>::split_at`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_at) [§](https://doc.rust-lang.org/stable/releases.html#cargo-21) Cargo ------------------------------------------------------------------ * [Allow named debuginfo options in `Cargo.toml`.](https://github.com/rust-lang/cargo/pull/11958/) * [Add `workspace_default_members` to the output of `cargo metadata`.](https://github.com/rust-lang/cargo/pull/11978/) * [Automatically inherit workspace fields when running `cargo new`/`cargo init`.](https://github.com/rust-lang/cargo/pull/12069/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-16) Rustdoc ---------------------------------------------------------------------- * [Add a new `rustdoc::unescaped_backticks` lint for broken inline code.](https://github.com/rust-lang/rust/pull/105848/) * [Support strikethrough with single tildes.](https://github.com/rust-lang/rust/pull/111152/) (`~~old~~` vs. `~new~`) [§](https://doc.rust-lang.org/stable/releases.html#misc-3) Misc --------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-20) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Remove structural match from `TypeId`.](https://github.com/rust-lang/rust/pull/103291/) Code that uses a constant `TypeId` in a pattern will potentially be broken. Known cases have already been fixed – in particular, users of the `log` crate’s `kv_unstable` feature should update to `log v0.4.18` or later. * [Add a `sysroot` crate to represent the standard library crates.](https://github.com/rust-lang/rust/pull/108865/) This does not affect stable users, but may require adjustment in tools that build their own standard library. * [Cargo optimizes its usage under `rustup`.](https://github.com/rust-lang/cargo/pull/11917/) When Cargo detects it will run `rustc` pointing to a rustup proxy, it’ll try bypassing the proxy and use the underlying binary directly. There are assumptions around the interaction with rustup and `RUSTUP_TOOLCHAIN`. However, it’s not expected to affect normal users. * [When querying a package, Cargo tries only the original name, all hyphens, and all underscores to handle misspellings.](https://github.com/rust-lang/cargo/pull/12083/) Previously, Cargo tried each combination of hyphens and underscores, causing excessive requests to crates.io. * Cargo now [disallows `RUSTUP_HOME`](https://github.com/rust-lang/cargo/pull/12101/) and [`RUSTUP_TOOLCHAIN`](https://github.com/rust-lang/cargo/pull/12107/) in the `[env]` configuration table. This is considered to be not a use case Cargo would like to support, since it will likely cause problems or lead to confusion. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-13) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. [§](https://doc.rust-lang.org/stable/releases.html#version-1700-2023-06-01) Version 1.70.0 (2023-06-01) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-22) Language ------------------------------------------------------------------------ * [Relax ordering rules for `asm!` operands](https://github.com/rust-lang/rust/pull/105798/) * [Properly allow macro expanded `format_args` invocations to uses captures](https://github.com/rust-lang/rust/pull/106505/) * [Lint ambiguous glob re-exports](https://github.com/rust-lang/rust/pull/107880/) * [Perform const and unsafe checking for expressions in `let _ = expr` position.](https://github.com/rust-lang/rust/pull/102256/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-22) Compiler ------------------------------------------------------------------------ * [Extend -Cdebuginfo with new options and named aliases](https://github.com/rust-lang/rust/pull/109808/) This provides a smaller version of debuginfo for cases that only need line number information (`-Cdebuginfo=line-tables-only`), which may eventually become the default for `-Cdebuginfo=1`. * [Make `unused_allocation` lint against `Box::new` too](https://github.com/rust-lang/rust/pull/104363/) * [Detect uninhabited types early in const eval](https://github.com/rust-lang/rust/pull/109435/) * [Switch to LLD as default linker for {arm,thumb}v4t-none-eabi](https://github.com/rust-lang/rust/pull/109721/) * [Add tier 3 target `loongarch64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/96971) * [Add tier 3 target for `i586-pc-nto-qnx700` (QNX Neutrino RTOS, version 7.0)](https://github.com/rust-lang/rust/pull/109173/) , * [Insert alignment checks for pointer dereferences as debug assertions](https://github.com/rust-lang/rust/pull/98112) This catches undefined behavior at runtime, and may cause existing code to fail. Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-22) Libraries -------------------------------------------------------------------------- * [Document NonZeroXxx layout guarantees](https://github.com/rust-lang/rust/pull/94786/) * [Windows: make `Command` prefer non-verbatim paths](https://github.com/rust-lang/rust/pull/96391/) * [Implement Default for some alloc/core iterators](https://github.com/rust-lang/rust/pull/99929/) * [Fix handling of trailing bare CR in str::lines](https://github.com/rust-lang/rust/pull/100311/) * [allow negative numeric literals in `concat!`](https://github.com/rust-lang/rust/pull/106844/) * [Add documentation about the memory layout of `Cell`](https://github.com/rust-lang/rust/pull/106921/) * [Use `partial_cmp` to implement tuple `lt`/`le`/`ge`/`gt`](https://github.com/rust-lang/rust/pull/108157/) * [Stabilize `atomic_as_ptr`](https://github.com/rust-lang/rust/pull/108419/) * [Stabilize `nonnull_slice_from_raw_parts`](https://github.com/rust-lang/rust/pull/97506/) * [Partial stabilization of `once_cell`](https://github.com/rust-lang/rust/pull/105587/) * [Stabilize `nonzero_min_max`](https://github.com/rust-lang/rust/pull/106633/) * [Flatten/inline format\_args!() and (string and int) literal arguments into format\_args!()](https://github.com/rust-lang/rust/pull/106824/) * [Stabilize movbe target feature](https://github.com/rust-lang/rust/pull/107711/) * [don’t splice from files into pipes in io::copy](https://github.com/rust-lang/rust/pull/108283/) * [Add a builtin unstable `FnPtr` trait that is implemented for all function pointers](https://github.com/rust-lang/rust/pull/108080/) This extends `Debug`, `Pointer`, `Hash`, `PartialEq`, `Eq`, `PartialOrd`, and `Ord` implementations for function pointers with all ABIs. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-22) Stabilized APIs -------------------------------------------------------------------------------------- * [`NonZero*::MIN/MAX`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroI8.html#associatedconstant.MIN) * [`BinaryHeap::retain`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.retain) * [`Default for std::collections::binary_heap::IntoIter`](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.IntoIter.html) * [`Default for std::collections::btree_map::{IntoIter, Iter, IterMut}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoIter.html) * [`Default for std::collections::btree_map::{IntoKeys, Keys}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoKeys.html) * [`Default for std::collections::btree_map::{IntoValues, Values}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoValues.html) * [`Default for std::collections::btree_map::Range`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.Range.html) * [`Default for std::collections::btree_set::{IntoIter, Iter}`](https://doc.rust-lang.org/stable/std/collections/btree_set/struct.IntoIter.html) * [`Default for std::collections::btree_set::Range`](https://doc.rust-lang.org/stable/std/collections/btree_set/struct.Range.html) * [`Default for std::collections::linked_list::{IntoIter, Iter, IterMut}`](https://doc.rust-lang.org/stable/alloc/collections/linked_list/struct.IntoIter.html) * [`Default for std::vec::IntoIter`](https://doc.rust-lang.org/stable/alloc/vec/struct.IntoIter.html#impl-Default-for-IntoIter%3CT,+A%3E) * [`Default for std::iter::Chain`](https://doc.rust-lang.org/stable/std/iter/struct.Chain.html) * [`Default for std::iter::Cloned`](https://doc.rust-lang.org/stable/std/iter/struct.Cloned.html) * [`Default for std::iter::Copied`](https://doc.rust-lang.org/stable/std/iter/struct.Copied.html) * [`Default for std::iter::Enumerate`](https://doc.rust-lang.org/stable/std/iter/struct.Enumerate.html) * [`Default for std::iter::Flatten`](https://doc.rust-lang.org/stable/std/iter/struct.Flatten.html) * [`Default for std::iter::Fuse`](https://doc.rust-lang.org/stable/std/iter/struct.Fuse.html) * [`Default for std::iter::Rev`](https://doc.rust-lang.org/stable/std/iter/struct.Rev.html) * [`Default for std::slice::Iter`](https://doc.rust-lang.org/stable/std/slice/struct.Iter.html) * [`Default for std::slice::IterMut`](https://doc.rust-lang.org/stable/std/slice/struct.IterMut.html) * [`Rc::into_inner`](https://doc.rust-lang.org/stable/alloc/rc/struct.Rc.html#method.into_inner) * [`Arc::into_inner`](https://doc.rust-lang.org/stable/alloc/sync/struct.Arc.html#method.into_inner) * [`std::cell::OnceCell`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html) * [`Option::is_some_and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.is_some_and) * [`NonNull::slice_from_raw_parts`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.slice_from_raw_parts) * [`Result::is_ok_and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_ok_and) * [`Result::is_err_and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_err_and) * [`std::sync::atomic::Atomic*::as_ptr`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU8.html#method.as_ptr) * [`std::io::IsTerminal`](https://doc.rust-lang.org/stable/std/io/trait.IsTerminal.html) * [`std::os::linux::net::SocketAddrExt`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.SocketAddrExt.html) * [`std::os::unix::net::UnixDatagram::bind_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixDatagram.html#method.bind_addr) * [`std::os::unix::net::UnixDatagram::connect_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixDatagram.html#method.connect_addr) * [`std::os::unix::net::UnixDatagram::send_to_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixDatagram.html#method.send_to_addr) * [`std::os::unix::net::UnixListener::bind_addr`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UnixListener.html#method.bind_addr) * [`std::path::Path::as_mut_os_str`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.as_mut_os_str) * [`std::sync::OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-22) Cargo ------------------------------------------------------------------ * [Add `CARGO_PKG_README`](https://github.com/rust-lang/cargo/pull/11645/) * [Make `sparse` the default protocol for crates.io](https://github.com/rust-lang/cargo/pull/11791/) * [Accurately show status when downgrading dependencies](https://github.com/rust-lang/cargo/pull/11839/) * [Use registry.default for login/logout](https://github.com/rust-lang/cargo/pull/11949/) * [Stabilize `cargo logout`](https://github.com/rust-lang/cargo/pull/11950/) [§](https://doc.rust-lang.org/stable/releases.html#misc-4) Misc --------------------------------------------------------------- * [Stabilize rustdoc `--test-run-directory`](https://github.com/rust-lang/rust/pull/103682/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-21) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Prevent stable `libtest` from supporting `-Zunstable-options`](https://github.com/rust-lang/rust/pull/109044/) * [Perform const and unsafe checking for expressions in `let _ = expr` position.](https://github.com/rust-lang/rust/pull/102256/) * [WebAssembly targets enable `sign-ext` and `mutable-globals` features in codegen](https://github.com/rust-lang/rust/issues/109807) This may cause incompatibility with older execution environments. * [Insert alignment checks for pointer dereferences as debug assertions](https://github.com/rust-lang/rust/pull/98112) This catches undefined behavior at runtime, and may cause existing code to fail. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-14) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Upgrade to LLVM 16](https://github.com/rust-lang/rust/pull/109474/) * [Use SipHash-1-3 instead of SipHash-2-4 for StableHasher](https://github.com/rust-lang/rust/pull/107925/) [§](https://doc.rust-lang.org/stable/releases.html#version-1690-2023-04-20) Version 1.69.0 (2023-04-20) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-23) Language ------------------------------------------------------------------------ * [Deriving built-in traits on packed structs works with `Copy` fields.](https://github.com/rust-lang/rust/pull/104429/) * [Stabilize the `cmpxchg16b` target feature on x86 and x86\_64.](https://github.com/rust-lang/rust/pull/106774/) * [Improve analysis of trait bounds for associated types.](https://github.com/rust-lang/rust/pull/103695/) * [Allow associated types to be used as union fields.](https://github.com/rust-lang/rust/pull/106938/) * [Allow `Self: Autotrait` bounds on dyn-safe trait methods.](https://github.com/rust-lang/rust/pull/107082/) * [Treat `str` as containing `[u8]` for auto trait purposes.](https://github.com/rust-lang/rust/pull/107941/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-23) Compiler ------------------------------------------------------------------------ * [Upgrade `*-pc-windows-gnu` on CI to mingw-w64 v10 and GCC 12.2.](https://github.com/rust-lang/rust/pull/100178/) * [Rework min\_choice algorithm of member constraints.](https://github.com/rust-lang/rust/pull/105300/) * [Support `true` and `false` as boolean flags in compiler arguments.](https://github.com/rust-lang/rust/pull/107043/) * [Default `repr(C)` enums to `c_int` size.](https://github.com/rust-lang/rust/pull/107592/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-23) Libraries -------------------------------------------------------------------------- * [Implement the unstable `DispatchFromDyn` for cell types, allowing downstream experimentation with custom method receivers.](https://github.com/rust-lang/rust/pull/97373/) * [Document that `fmt::Arguments::as_str()` may return `Some(_)` in more cases after optimization, subject to change.](https://github.com/rust-lang/rust/pull/106823/) * [Implement `AsFd` and `AsRawFd` for `Rc`.](https://github.com/rust-lang/rust/pull/107317/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-23) Stabilized APIs -------------------------------------------------------------------------------------- * [`CStr::from_bytes_until_nul`](https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html#method.from_bytes_until_nul) * [`core::ffi::FromBytesUntilNulError`](https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesUntilNulError.html) These APIs are now stable in const contexts: * [`SocketAddr::new`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.new) * [`SocketAddr::ip`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.ip) * [`SocketAddr::port`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.port) * [`SocketAddr::is_ipv4`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv4) * [`SocketAddr::is_ipv6`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv6) * [`SocketAddrV4::new`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.new) * [`SocketAddrV4::ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.ip) * [`SocketAddrV4::port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.port) * [`SocketAddrV6::new`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.new) * [`SocketAddrV6::ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.ip) * [`SocketAddrV6::port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.port) * [`SocketAddrV6::flowinfo`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.flowinfo) * [`SocketAddrV6::scope_id`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.scope_id) [§](https://doc.rust-lang.org/stable/releases.html#cargo-23) Cargo ------------------------------------------------------------------ * [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) * [Cargo now suggests `cargo add` if you try to install a library crate.](https://github.com/rust-lang/cargo/pull/11410/) * [Cargo now sets the `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-17) Rustdoc ---------------------------------------------------------------------- * [Vertically compact trait bound formatting.](https://github.com/rust-lang/rust/pull/102842/) * [Only include stable lints in `rustdoc::all` group.](https://github.com/rust-lang/rust/pull/106316/) * [Compute maximum Levenshtein distance based on the query.](https://github.com/rust-lang/rust/pull/107141/) * [Remove inconsistently-present sidebar tooltips.](https://github.com/rust-lang/rust/pull/107490/) * [Search by macro when query ends with `!`.](https://github.com/rust-lang/rust/pull/108143/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-22) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The `rust-analysis` component from `rustup` now only contains a warning placeholder.](https://github.com/rust-lang/rust/pull/101841/) This was primarily intended for RLS, and the corresponding `-Zsave-analysis` flag has been removed from the compiler as well. * [Unaligned references to packed fields are now a hard error.](https://github.com/rust-lang/rust/pull/102513/) This has been a warning since 1.53, and denied by default with a future-compatibility warning since 1.62. * [Update the minimum external LLVM to 14.](https://github.com/rust-lang/rust/pull/107573/) * [Cargo now emits errors on invalid characters in a registry token.](https://github.com/rust-lang/cargo/pull/11600/) * [When `default-features` is set to false of a workspace dependency, and an inherited dependency of a member has `default-features = true`, Cargo will enable default features of that dependency.](https://github.com/rust-lang/cargo/pull/11409/) * [Cargo denies `CARGO_HOME` in the `[env]` configuration table. Cargo itself doesn’t pick up this value, but recursive calls to cargo would, which was not intended.](https://github.com/rust-lang/cargo/pull/11644/) * [Debuginfo for build dependencies is now off if not explicitly set. This is expected to improve the overall build time.](https://github.com/rust-lang/cargo/pull/11252/) * [The Rust distribution no longer always includes rustdoc](https://github.com/rust-lang/rust/pull/106886) If `tools = [...]` is set in bootstrap.toml, we will respect a missing rustdoc in that list. By default rustdoc remains included. To retain the prior behavior explicitly add `"rustdoc"` to the list. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-15) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Move `format_args!()` into AST (and expand it during AST lowering)](https://github.com/rust-lang/rust/pull/106745/) [§](https://doc.rust-lang.org/stable/releases.html#version-1682-2023-03-28) Version 1.68.2 (2023-03-28) ======================================================================================================= * [Update the GitHub RSA host key bundled within Cargo](https://github.com/rust-lang/cargo/pull/11883) . The key was [rotated by GitHub](https://github.blog/2023-03-23-we-updated-our-rsa-ssh-host-key/) on 2023-03-24 after the old one leaked. * [Mark the old GitHub RSA host key as revoked](https://github.com/rust-lang/cargo/pull/11889) . This will prevent Cargo from accepting the leaked key even when trusted by the system. * [Add support for `@revoked` and a better error message for `@cert-authority` in Cargo’s SSH host key verification](https://github.com/rust-lang/cargo/pull/11635) [§](https://doc.rust-lang.org/stable/releases.html#version-1681-2023-03-23) Version 1.68.1 (2023-03-23) ======================================================================================================= * [Fix miscompilation in produced Windows MSVC artifacts](https://github.com/rust-lang/rust/pull/109094) This was introduced by enabling ThinLTO for the distributed rustc which led to miscompilations in the resulting binary. Currently this is believed to be limited to the -Zdylib-lto flag used for rustc compilation, rather than a general bug in ThinLTO, so only rustc artifacts should be affected. * [Fix –enable-local-rust builds](https://github.com/rust-lang/rust/pull/109111/) * [Treat `$prefix-clang` as `clang` in linker detection code](https://github.com/rust-lang/rust/pull/109156) * [Fix panic in compiler code](https://github.com/rust-lang/rust/pull/108162) [§](https://doc.rust-lang.org/stable/releases.html#version-1680-2023-03-09) Version 1.68.0 (2023-03-09) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-24) Language ------------------------------------------------------------------------ * [Stabilize default\_alloc\_error\_handler](https://github.com/rust-lang/rust/pull/102318/) This allows usage of `alloc` on stable without requiring the definition of a handler for allocation failure. Defining custom handlers is still unstable. * [Stabilize `efiapi` calling convention.](https://github.com/rust-lang/rust/pull/105795/) * [Remove implicit promotion for types with drop glue](https://github.com/rust-lang/rust/pull/105085/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-24) Compiler ------------------------------------------------------------------------ * [Change `bindings_with_variant_name` to deny-by-default](https://github.com/rust-lang/rust/pull/104154/) * [Allow .. to be parsed as let initializer](https://github.com/rust-lang/rust/pull/105701/) * [Add `armv7-sony-vita-newlibeabihf` as a tier 3 target](https://github.com/rust-lang/rust/pull/105712/) * [Always check alignment during compile-time const evaluation](https://github.com/rust-lang/rust/pull/104616/) * [Disable “split dwarf inlining” by default.](https://github.com/rust-lang/rust/pull/106709/) * [Add vendor to Fuchsia’s target triple](https://github.com/rust-lang/rust/pull/106429/) * [Enable sanitizers for s390x-linux](https://github.com/rust-lang/rust/pull/107127/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-24) Libraries -------------------------------------------------------------------------- * [Loosen the bound on the Debug implementation of Weak.](https://github.com/rust-lang/rust/pull/90291/) * [Make `std::task::Context` !Send and !Sync](https://github.com/rust-lang/rust/pull/95985/) * [PhantomData layout guarantees](https://github.com/rust-lang/rust/pull/104081/) * [Don’t derive Debug for `OnceWith` & `RepeatWith`](https://github.com/rust-lang/rust/pull/104163/) * [Implement DerefMut for PathBuf](https://github.com/rust-lang/rust/pull/105018/) * [Add O(1) `Vec -> VecDeque` conversion guarantee](https://github.com/rust-lang/rust/pull/105128/) * [Leak amplification for peek\_mut() to ensure BinaryHeap’s invariant is always met](https://github.com/rust-lang/rust/pull/105851/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-24) Stabilized APIs -------------------------------------------------------------------------------------- * [`{core,std}::pin::pin!`](https://doc.rust-lang.org/stable/std/pin/macro.pin.html) * [`impl From for {f32,f64}`](https://doc.rust-lang.org/stable/std/primitive.f32.html#impl-From%3Cbool%3E-for-f32) * [`std::path::MAIN_SEPARATOR_STR`](https://doc.rust-lang.org/stable/std/path/constant.MAIN_SEPARATOR_STR.html) * [`impl DerefMut for PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#impl-DerefMut-for-PathBuf) These APIs are now stable in const contexts: * [`VecDeque::new`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.new) [§](https://doc.rust-lang.org/stable/releases.html#cargo-24) Cargo ------------------------------------------------------------------ * [Stabilize sparse registry support for crates.io](https://github.com/rust-lang/cargo/pull/11224/) * [`cargo build --verbose` tells you more about why it recompiles.](https://github.com/rust-lang/cargo/pull/11407/) * [Show progress of crates.io index update even `net.git-fetch-with-cli` option enabled](https://github.com/rust-lang/cargo/pull/11579/) [§](https://doc.rust-lang.org/stable/releases.html#misc-5) Misc --------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-23) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Only support Android NDK 25 or newer](https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html) * [Add `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` to future-incompat report](https://github.com/rust-lang/rust/pull/103418/) * [Only specify `--target` by default for `-Zgcc-ld=lld` on wasm](https://github.com/rust-lang/rust/pull/101792/) * [Bump `IMPLIED_BOUNDS_ENTAILMENT` to Deny + ReportNow](https://github.com/rust-lang/rust/pull/106465/) * [`std::task::Context` no longer implements Send and Sync](https://github.com/rust-lang/rust/pull/95985) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-16) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Encode spans relative to the enclosing item](https://github.com/rust-lang/rust/pull/84762/) * [Don’t normalize in AstConv](https://github.com/rust-lang/rust/pull/101947/) * [Find the right lower bound region in the scenario of partial order relations](https://github.com/rust-lang/rust/pull/104765/) * [Fix impl block in const expr](https://github.com/rust-lang/rust/pull/104889/) * [Check ADT fields for copy implementations considering regions](https://github.com/rust-lang/rust/pull/105102/) * [rustdoc: simplify JS search routine by not messing with lev distance](https://github.com/rust-lang/rust/pull/105796/) * [Enable ThinLTO for rustc on `x86_64-pc-windows-msvc`](https://github.com/rust-lang/rust/pull/103591/) * [Enable ThinLTO for rustc on `x86_64-apple-darwin`](https://github.com/rust-lang/rust/pull/103647/) [§](https://doc.rust-lang.org/stable/releases.html#version-1671-2023-02-09) Version 1.67.1 (2023-02-09) ======================================================================================================= * [Fix interoperability with thin archives.](https://github.com/rust-lang/rust/pull/107360) * [Fix an internal error in the compiler build process.](https://github.com/rust-lang/rust/pull/105624) * [Downgrade `clippy::uninlined_format_args` to pedantic.](https://github.com/rust-lang/rust-clippy/pull/10265) [§](https://doc.rust-lang.org/stable/releases.html#version-1670-2023-01-26) Version 1.67.0 (2023-01-26) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-25) Language ------------------------------------------------------------------------ * [Make `Sized` predicates coinductive, allowing cycles.](https://github.com/rust-lang/rust/pull/100386/) * [`#[must_use]` annotations on `async fn` also affect the `Future::Output`.](https://github.com/rust-lang/rust/pull/100633/) * [Elaborate supertrait obligations when deducing closure signatures.](https://github.com/rust-lang/rust/pull/101834/) * [Invalid literals are no longer an error under `cfg(FALSE)`.](https://github.com/rust-lang/rust/pull/102944/) * [Unreserve braced enum variants in value namespace.](https://github.com/rust-lang/rust/pull/103578/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-25) Compiler ------------------------------------------------------------------------ * [Enable varargs support for calling conventions other than `C` or `cdecl`.](https://github.com/rust-lang/rust/pull/97971/) * [Add new MIR constant propagation based on dataflow analysis.](https://github.com/rust-lang/rust/pull/101168/) * [Optimize field ordering by grouping m\*2^n-sized fields with equivalently aligned ones.](https://github.com/rust-lang/rust/pull/102750/) * [Stabilize native library modifier `verbatim`.](https://github.com/rust-lang/rust/pull/104360/) Added, updated, and removed targets: * [Add a tier 3 target for PowerPC on AIX](https://github.com/rust-lang/rust/pull/102293/) , `powerpc64-ibm-aix`. * [Add a tier 3 target for the Sony PlayStation 1](https://github.com/rust-lang/rust/pull/102689/) , `mipsel-sony-psx`. * [Add tier 3 `no_std` targets for the QNX Neutrino RTOS](https://github.com/rust-lang/rust/pull/102701/) , `aarch64-unknown-nto-qnx710` and `x86_64-pc-nto-qnx710`. * [Promote UEFI targets to tier 2](https://github.com/rust-lang/rust/pull/103933/) , `aarch64-unknown-uefi`, `i686-unknown-uefi`, and `x86_64-unknown-uefi`. * [Remove tier 3 `linuxkernel` targets](https://github.com/rust-lang/rust/pull/104015/) (not used by the actual kernel). Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-25) Libraries -------------------------------------------------------------------------- * [Merge `crossbeam-channel` into `std::sync::mpsc`.](https://github.com/rust-lang/rust/pull/93563/) * [Fix inconsistent rounding of 0.5 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) * [Derive `Eq` and `Hash` for `ControlFlow`.](https://github.com/rust-lang/rust/pull/103084/) * [Don’t build `compiler_builtins` with `-C panic=abort`.](https://github.com/rust-lang/rust/pull/103786/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-25) Stabilized APIs -------------------------------------------------------------------------------------- * [`{integer}::checked_ilog`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog) * [`{integer}::checked_ilog2`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog2) * [`{integer}::checked_ilog10`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.checked_ilog10) * [`{integer}::ilog`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog) * [`{integer}::ilog2`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog2) * [`{integer}::ilog10`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.ilog10) * [`NonZeroU*::ilog2`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#method.ilog2) * [`NonZeroU*::ilog10`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#method.ilog10) * [`NonZero*::BITS`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html#associatedconstant.BITS) These APIs are now stable in const contexts: * [`char::from_u32`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_u32) * [`char::from_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_digit) * [`char::to_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_digit) * [`core::char::from_u32`](https://doc.rust-lang.org/stable/core/char/fn.from_u32.html) * [`core::char::from_digit`](https://doc.rust-lang.org/stable/core/char/fn.from_digit.html) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-24) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The layout of `repr(Rust)` types now groups m\*2^n-sized fields with equivalently aligned ones.](https://github.com/rust-lang/rust/pull/102750/) This is intended to be an optimization, but it is also known to increase type sizes in a few cases for the placement of enum tags. As a reminder, the layout of `repr(Rust)` types is an implementation detail, subject to change. * [0.5 now rounds to 0 when formatted to 0 decimal places.](https://github.com/rust-lang/rust/pull/102935/) This makes it consistent with the rest of floating point formatting that rounds ties toward even digits. * [Chains of `&&` and `||` will now drop temporaries from their sub-expressions in evaluation order, left-to-right.](https://github.com/rust-lang/rust/pull/103293/) Previously, it was “twisted” such that the _first_ expression dropped its temporaries _last_, after all of the other expressions dropped in order. * [Underscore suffixes on string literals are now a hard error.](https://github.com/rust-lang/rust/pull/103914/) This has been a future-compatibility warning since 1.20.0. * [Stop passing `-export-dynamic` to `wasm-ld`.](https://github.com/rust-lang/rust/pull/105405/) * [`main` is now mangled as `__main_void` on `wasm32-wasi`.](https://github.com/rust-lang/rust/pull/105468/) * [Cargo now emits an error if there are multiple registries in the configuration with the same index URL.](https://github.com/rust-lang/cargo/pull/10592) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-17) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Rewrite LLVM’s archive writer in Rust.](https://github.com/rust-lang/rust/pull/97485/) [§](https://doc.rust-lang.org/stable/releases.html#version-1661-2023-01-10) Version 1.66.1 (2023-01-10) ======================================================================================================= * Added validation of SSH host keys for git URLs in Cargo ([CVE-2022-46176](https://www.cve.org/CVERecord?id=CVE-2022-46176) ) [§](https://doc.rust-lang.org/stable/releases.html#version-1660-2022-12-15) Version 1.66.0 (2022-12-15) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-26) Language ------------------------------------------------------------------------ * [Permit specifying explicit discriminants on all `repr(Int)` enums](https://github.com/rust-lang/rust/pull/95710/) #[repr(u8)] enum Foo { A(u8) = 0, B(i8) = 1, C(bool) = 42, } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Brepr(u8)%5D%0A++++enum+Foo+%7B%0A++++++++A(u8)+=+0,%0A++++++++B(i8)+=+1,%0A++++++++C(bool)+=+42,%0A++++%7D%0A%7D&edition=2015 "Run code") * [Allow transmutes between the same type differing only in lifetimes](https://github.com/rust-lang/rust/pull/101520/) * [Change constant evaluation errors from a deny-by-default lint to a hard error](https://github.com/rust-lang/rust/pull/102091/) * [Trigger `must_use` on `impl Trait` for supertraits](https://github.com/rust-lang/rust/pull/102287/) This makes `impl ExactSizeIterator` respect the existing `#[must_use]` annotation on `Iterator`. * [Allow `..=X` in patterns](https://github.com/rust-lang/rust/pull/102275/) * [Uplift `clippy::for_loops_over_fallibles` lint into rustc](https://github.com/rust-lang/rust/pull/99696/) * [Stabilize `sym` operands in inline assembly](https://github.com/rust-lang/rust/pull/103168/) * [Update to Unicode 15](https://github.com/rust-lang/rust/pull/101912/) * [Opaque types no longer imply lifetime bounds](https://github.com/rust-lang/rust/pull/95474/) This is a soundness fix which may break code that was erroneously relying on this behavior. [§](https://doc.rust-lang.org/stable/releases.html#compiler-26) Compiler ------------------------------------------------------------------------ * [Add armv5te-none-eabi and thumbv5te-none-eabi tier 3 targets](https://github.com/rust-lang/rust/pull/101329/) * Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. * [Add support for linking against macOS universal libraries](https://github.com/rust-lang/rust/pull/98736) [§](https://doc.rust-lang.org/stable/releases.html#libraries-26) Libraries -------------------------------------------------------------------------- * [Fix `#[derive(Default)]` on a generic `#[default]` enum adding unnecessary `Default` bounds](https://github.com/rust-lang/rust/pull/101040/) * [Update to Unicode 15](https://github.com/rust-lang/rust/pull/101821/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-26) Stabilized APIs -------------------------------------------------------------------------------------- * [`proc_macro::Span::source_text`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.source_text) * [`uX::{checked_add_signed, overflowing_add_signed, saturating_add_signed, wrapping_add_signed}`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.checked_add_signed) * [`iX::{checked_add_unsigned, overflowing_add_unsigned, saturating_add_unsigned, wrapping_add_unsigned}`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.checked_add_unsigned) * [`iX::{checked_sub_unsigned, overflowing_sub_unsigned, saturating_sub_unsigned, wrapping_sub_unsigned}`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.checked_sub_unsigned) * [`BTreeSet::{first, last, pop_first, pop_last}`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html#method.first) * [`BTreeMap::{first_key_value, last_key_value, first_entry, last_entry, pop_first, pop_last}`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html#method.first_key_value) * [Add `AsFd` implementations for stdio lock types on WASI.](https://github.com/rust-lang/rust/pull/101768/) * [`impl TryFrom> for Box<[T; N]>`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#impl-TryFrom%3CVec%3CT%2C%20Global%3E%3E-for-Box%3C%5BT%3B%20N%5D%2C%20Global%3E) * [`core::hint::black_box`](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html) * [`Duration::try_from_secs_{f32,f64}`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.try_from_secs_f32) * [`Option::unzip`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unzip) * [`std::os::fd`](https://doc.rust-lang.org/stable/std/os/fd/index.html) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-18) Rustdoc ---------------------------------------------------------------------- * [Add Rustdoc warning for invalid HTML tags in the documentation](https://github.com/rust-lang/rust/pull/101720/) [§](https://doc.rust-lang.org/stable/releases.html#cargo-25) Cargo ------------------------------------------------------------------ * [Added `cargo remove` to remove dependencies from Cargo.toml](https://doc.rust-lang.org/nightly/cargo/commands/cargo-remove.html) * [`cargo publish` now waits for the new version to be downloadable before exiting](https://github.com/rust-lang/cargo/pull/11062) See [detailed release notes](https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-166-2022-12-15) for more. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-25) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Only apply `ProceduralMasquerade` hack to older versions of `rental`](https://github.com/rust-lang/rust/pull/94063/) * [Don’t export `__heap_base` and `__data_end` on wasm32-wasi.](https://github.com/rust-lang/rust/pull/102385/) * [Don’t export `__wasm_init_memory` on WebAssembly.](https://github.com/rust-lang/rust/pull/102426/) * [Only export `__tls_*` on wasm32-unknown-unknown.](https://github.com/rust-lang/rust/pull/102440/) * [Don’t link to `libresolv` in libstd on Darwin](https://github.com/rust-lang/rust/pull/102766/) * [Update libstd’s libc to 0.2.135 (to make `libstd` no longer pull in `libiconv.dylib` on Darwin)](https://github.com/rust-lang/rust/pull/103277/) * [Opaque types no longer imply lifetime bounds](https://github.com/rust-lang/rust/pull/95474/) This is a soundness fix which may break code that was erroneously relying on this behavior. * [Make `order_dependent_trait_objects` show up in future-breakage reports](https://github.com/rust-lang/rust/pull/102635/) * [Change std::process::Command spawning to default to inheriting the parent’s signal mask](https://github.com/rust-lang/rust/pull/101077/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-18) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Enable BOLT for LLVM compilation](https://github.com/rust-lang/rust/pull/94381/) * [Enable LTO for rustc\_driver.so](https://github.com/rust-lang/rust/pull/101403/) [§](https://doc.rust-lang.org/stable/releases.html#version-1650-2022-11-03) Version 1.65.0 (2022-11-03) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-27) Language ------------------------------------------------------------------------ * [Error on `as` casts of enums with `#[non_exhaustive]` variants](https://github.com/rust-lang/rust/pull/92744/) * [Stabilize `let else`](https://github.com/rust-lang/rust/pull/93628/) * [Stabilize generic associated types (GATs)](https://github.com/rust-lang/rust/pull/96709/) * [Add lints `let_underscore_drop` and `let_underscore_lock` from Clippy](https://github.com/rust-lang/rust/pull/97739/) * [Stabilize `break`ing from arbitrary labeled blocks (“label-break-value”)](https://github.com/rust-lang/rust/pull/99332/) * [Uninitialized integers, floats, and raw pointers are now considered immediate UB](https://github.com/rust-lang/rust/pull/98919/) . Usage of `MaybeUninit` is the correct way to work with uninitialized memory. * [Stabilize raw-dylib for Windows x86\_64, aarch64, and thumbv7a](https://github.com/rust-lang/rust/pull/99916/) * [Do not allow `Drop` impl on foreign ADTs](https://github.com/rust-lang/rust/pull/99576/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-27) Compiler ------------------------------------------------------------------------ * [Stabilize -Csplit-debuginfo on Linux](https://github.com/rust-lang/rust/pull/98051/) * [Use niche-filling optimization even when multiple variants have data](https://github.com/rust-lang/rust/pull/94075/) * [Associated type projections are now verified to be well-formed prior to resolving the underlying type](https://github.com/rust-lang/rust/pull/99217/#issuecomment-1209365630) * [Stringify non-shorthand visibility correctly](https://github.com/rust-lang/rust/pull/100350/) * [Normalize struct field types when unsizing](https://github.com/rust-lang/rust/pull/101831/) * [Update to LLVM 15](https://github.com/rust-lang/rust/pull/99464/) * [Fix aarch64 call abi to correctly zeroext when needed](https://github.com/rust-lang/rust/pull/97800/) * [debuginfo: Generalize C++-like encoding for enums](https://github.com/rust-lang/rust/pull/98393/) * [Add `special_module_name` lint](https://github.com/rust-lang/rust/pull/94467/) * [Add support for generating unique profraw files by default when using `-C instrument-coverage`](https://github.com/rust-lang/rust/pull/100384/) * [Allow dynamic linking for iOS/tvOS targets](https://github.com/rust-lang/rust/pull/100636/) New targets: * [Add armv4t-none-eabi as a tier 3 target](https://github.com/rust-lang/rust/pull/100244/) * [Add powerpc64-unknown-openbsd and riscv64-unknown-openbsd as tier 3 targets](https://github.com/rust-lang/rust/pull/101025/) * Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-27) Libraries -------------------------------------------------------------------------- * [Don’t generate `PartialEq::ne` in derive(PartialEq)](https://github.com/rust-lang/rust/pull/98655/) * [Windows RNG: Use `BCRYPT_RNG_ALG_HANDLE` by default](https://github.com/rust-lang/rust/pull/101325/) * [Forbid mixing `System` with direct system allocator calls](https://github.com/rust-lang/rust/pull/101394/) * [Document no support for writing to non-blocking stdio/stderr](https://github.com/rust-lang/rust/pull/101416/) * [`std::layout::Layout` size must not overflow `isize::MAX` when rounded up to `align`](https://github.com/rust-lang/rust/pull/95295) This also changes the safety conditions on `Layout::from_size_align_unchecked`. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-27) Stabilized APIs -------------------------------------------------------------------------------------- * [`std::backtrace::Backtrace`](https://doc.rust-lang.org/stable/std/backtrace/struct.Backtrace.html) * [`Bound::as_ref`](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html#method.as_ref) * [`std::io::read_to_string`](https://doc.rust-lang.org/stable/std/io/fn.read_to_string.html) * [`<*const T>::cast_mut`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.cast_mut) * [`<*mut T>::cast_const`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.cast_const) These APIs are now stable in const contexts: * [`<*const T>::offset_from`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from) * [`<*mut T>::offset_from`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from) [§](https://doc.rust-lang.org/stable/releases.html#cargo-26) Cargo ------------------------------------------------------------------ * [Apply GitHub fast path even for partial hashes](https://github.com/rust-lang/cargo/pull/10807/) * [Do not add home bin path to PATH if it’s already there](https://github.com/rust-lang/cargo/pull/11023/) * [Take priority into account within the pending queue](https://github.com/rust-lang/cargo/pull/11032/) . This slightly optimizes job scheduling by Cargo, with typically small improvements on larger crate graph builds. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-26) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`std::layout::Layout` size must not overflow `isize::MAX` when rounded up to `align`](https://github.com/rust-lang/rust/pull/95295) . This also changes the safety conditions on `Layout::from_size_align_unchecked`. * [`PollFn` now only implements `Unpin` if the closure is `Unpin`](https://github.com/rust-lang/rust/pull/102737) . This is a possible breaking change if users were relying on the blanket unpin implementation. See discussion on the PR for details of why this change was made. * [Drop ExactSizeIterator impl from std::char::EscapeAscii](https://github.com/rust-lang/rust/pull/99880) This is a backwards-incompatible change to the standard library’s surface area, but is unlikely to affect real world usage. * [Do not consider a single repeated lifetime eligible for elision in the return type](https://github.com/rust-lang/rust/pull/103450) This behavior was unintentionally changed in 1.64.0, and this release reverts that change by making this an error again. * [Reenable disabled early syntax gates as future-incompatibility lints](https://github.com/rust-lang/rust/pull/99935/) * [Update the minimum external LLVM to 13](https://github.com/rust-lang/rust/pull/100460/) * [Don’t duplicate file descriptors into stdio fds](https://github.com/rust-lang/rust/pull/101426/) * [Sunset RLS](https://github.com/rust-lang/rust/pull/100863/) * [Deny usage of `#![cfg_attr(..., crate_type = ...)]` to set the crate type](https://github.com/rust-lang/rust/pull/99784/) This strengthens the forward compatibility lint deprecated\_cfg\_attr\_crate\_type\_name to deny. * [`llvm-has-rust-patches` allows setting the build system to treat the LLVM as having Rust-specific patches](https://github.com/rust-lang/rust/pull/101072) This option may need to be set for distributions that are building Rust with a patched LLVM via `llvm-config`, not the built-in LLVM. * Combining three or more languages (e.g. Objective C, C++ and Rust) into one binary may hit linker limitations when using `lld`. For more information, see [issue 102754](https://github.com/rust-lang/rust/issues/102754) . [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-19) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * [Add `x.sh` and `x.ps1` shell scripts](https://github.com/rust-lang/rust/pull/99992/) * [compiletest: use target cfg instead of hard-coded tables](https://github.com/rust-lang/rust/pull/100260/) * [Use object instead of LLVM for reading bitcode from rlibs](https://github.com/rust-lang/rust/pull/98100/) * [Enable MIR inlining for optimized compilations](https://github.com/rust-lang/rust/pull/91743) This provides a 3-10% improvement in compiletimes for real world crates. See [perf results](https://perf.rust-lang.org/compare.html?start=aedf78e56b2279cc869962feac5153b6ba7001ed&end=0075bb4fad68e64b6d1be06bf2db366c30bc75e1&stat=instructions:u) . [§](https://doc.rust-lang.org/stable/releases.html#version-1640-2022-09-22) Version 1.64.0 (2022-09-22) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-28) Language ------------------------------------------------------------------------ * [Unions with mutable references or tuples of allowed types are now allowed](https://github.com/rust-lang/rust/pull/97995/) * It is now considered valid to deallocate memory pointed to by a shared reference `&T` [if every byte in `T` is inside an `UnsafeCell`](https://github.com/rust-lang/rust/pull/98017/) * Unused tuple struct fields are now warned against in an allow-by-default lint, [`unused_tuple_struct_fields`](https://github.com/rust-lang/rust/pull/95977/) , similar to the existing warning for unused struct fields. This lint will become warn-by-default in the future. [§](https://doc.rust-lang.org/stable/releases.html#compiler-28) Compiler ------------------------------------------------------------------------ * [Add Nintendo Switch as tier 3 target](https://github.com/rust-lang/rust/pull/88991/) * Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. * [Only compile `#[used]` as llvm.compiler.used for ELF targets](https://github.com/rust-lang/rust/pull/93718/) * [Add the `--diagnostic-width` compiler flag to define the terminal width.](https://github.com/rust-lang/rust/pull/95635/) * [Add support for link-flavor `rust-lld` for iOS, tvOS and watchOS](https://github.com/rust-lang/rust/pull/98771/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-28) Libraries -------------------------------------------------------------------------- * [Remove restrictions on compare-exchange memory ordering.](https://github.com/rust-lang/rust/pull/98383/) * You can now `write!` or `writeln!` into an `OsString`: [Implement `fmt::Write` for `OsString`](https://github.com/rust-lang/rust/pull/97915/) * [Make RwLockReadGuard covariant](https://github.com/rust-lang/rust/pull/96820/) * [Implement `FusedIterator` for `std::net::[Into]Incoming`](https://github.com/rust-lang/rust/pull/97300/) * [`impl AsRawFd for {Arc,Box}`](https://github.com/rust-lang/rust/pull/97437/) * [`ptr::copy` and `ptr::swap` are doing untyped copies](https://github.com/rust-lang/rust/pull/97712/) * [Add cgroupv1 support to `available_parallelism`](https://github.com/rust-lang/rust/pull/97925/) * [Mitigate many incorrect uses of `mem::uninitialized`](https://github.com/rust-lang/rust/pull/99182/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-28) Stabilized APIs -------------------------------------------------------------------------------------- * [`future::IntoFuture`](https://doc.rust-lang.org/stable/std/future/trait.IntoFuture.html) * [`future::poll_fn`](https://doc.rust-lang.org/stable/std/future/fn.poll_fn.html) * [`task::ready!`](https://doc.rust-lang.org/stable/std/task/macro.ready.html) * [`num::NonZero*::checked_mul`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_mul) * [`num::NonZero*::checked_pow`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_pow) * [`num::NonZero*::saturating_mul`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.saturating_mul) * [`num::NonZero*::saturating_pow`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.saturating_pow) * [`num::NonZeroI*::abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.abs) * [`num::NonZeroI*::checked_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.checked_abs) * [`num::NonZeroI*::overflowing_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.overflowing_abs) * [`num::NonZeroI*::saturating_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.saturating_abs) * [`num::NonZeroI*::unsigned_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.unsigned_abs) * [`num::NonZeroI*::wrapping_abs`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroIsize.html#method.wrapping_abs) * [`num::NonZeroU*::checked_add`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_add) * [`num::NonZeroU*::checked_next_power_of_two`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.checked_next_power_of_two) * [`num::NonZeroU*::saturating_add`](https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize.html#method.saturating_add) * [`os::unix::process::CommandExt::process_group`](https://doc.rust-lang.org/stable/std/os/unix/process/trait.CommandExt.html#tymethod.process_group) * [`os::windows::fs::FileTypeExt::is_symlink_dir`](https://doc.rust-lang.org/stable/std/os/windows/fs/trait.FileTypeExt.html#tymethod.is_symlink_dir) * [`os::windows::fs::FileTypeExt::is_symlink_file`](https://doc.rust-lang.org/stable/std/os/windows/fs/trait.FileTypeExt.html#tymethod.is_symlink_file) These types were previously stable in `std::ffi`, but are now also available in `core` and `alloc`: * [`core::ffi::CStr`](https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html) * [`core::ffi::FromBytesWithNulError`](https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesWithNulError.html) * [`alloc::ffi::CString`](https://doc.rust-lang.org/stable/alloc/ffi/struct.CString.html) * [`alloc::ffi::FromVecWithNulError`](https://doc.rust-lang.org/stable/alloc/ffi/struct.FromVecWithNulError.html) * [`alloc::ffi::IntoStringError`](https://doc.rust-lang.org/stable/alloc/ffi/struct.IntoStringError.html) * [`alloc::ffi::NulError`](https://doc.rust-lang.org/stable/alloc/ffi/struct.NulError.html) These types were previously stable in `std::os::raw`, but are now also available in `core::ffi` and `std::ffi`: * [`ffi::c_char`](https://doc.rust-lang.org/stable/std/ffi/type.c_char.html) * [`ffi::c_double`](https://doc.rust-lang.org/stable/std/ffi/type.c_double.html) * [`ffi::c_float`](https://doc.rust-lang.org/stable/std/ffi/type.c_float.html) * [`ffi::c_int`](https://doc.rust-lang.org/stable/std/ffi/type.c_int.html) * [`ffi::c_long`](https://doc.rust-lang.org/stable/std/ffi/type.c_long.html) * [`ffi::c_longlong`](https://doc.rust-lang.org/stable/std/ffi/type.c_longlong.html) * [`ffi::c_schar`](https://doc.rust-lang.org/stable/std/ffi/type.c_schar.html) * [`ffi::c_short`](https://doc.rust-lang.org/stable/std/ffi/type.c_short.html) * [`ffi::c_uchar`](https://doc.rust-lang.org/stable/std/ffi/type.c_uchar.html) * [`ffi::c_uint`](https://doc.rust-lang.org/stable/std/ffi/type.c_uint.html) * [`ffi::c_ulong`](https://doc.rust-lang.org/stable/std/ffi/type.c_ulong.html) * [`ffi::c_ulonglong`](https://doc.rust-lang.org/stable/std/ffi/type.c_ulonglong.html) * [`ffi::c_ushort`](https://doc.rust-lang.org/stable/std/ffi/type.c_ushort.html) These APIs are now usable in const contexts: * [`slice::from_raw_parts`](https://doc.rust-lang.org/stable/core/slice/fn.from_raw_parts.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-27) Cargo ------------------------------------------------------------------ * [Packages can now inherit settings from the workspace so that the settings can be centralized in one place.](https://github.com/rust-lang/cargo/pull/10859) See [`workspace.package`](https://doc.rust-lang.org/nightly/cargo/reference/workspaces.html#the-workspacepackage-table) and [`workspace.dependencies`](https://doc.rust-lang.org/nightly/cargo/reference/workspaces.html#the-workspacedependencies-table) for more details on how to define these common settings. * [Cargo commands can now accept multiple `--target` flags to build for multiple targets at once](https://github.com/rust-lang/cargo/pull/10766) , and the [`build.target`](https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildtarget) config option may now take an array of multiple targets. * [The `--jobs` argument can now take a negative number to count backwards from the max CPUs.](https://github.com/rust-lang/cargo/pull/10844) * [`cargo add` will now update `Cargo.lock`.](https://github.com/rust-lang/cargo/pull/10902) * [Added](https://github.com/rust-lang/cargo/pull/10838) the [`--crate-type`](https://doc.rust-lang.org/nightly/cargo/commands/cargo-rustc.html#option-cargo-rustc---crate-type) flag to `cargo rustc` to override the crate type. * [Significantly improved the performance fetching git dependencies from GitHub when using a hash in the `rev` field.](https://github.com/rust-lang/cargo/pull/10079) [§](https://doc.rust-lang.org/stable/releases.html#misc-6) Misc --------------------------------------------------------------- * [The `rust-analyzer` rustup component is now available on the stable channel.](https://github.com/rust-lang/rust/pull/98640/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-27) Compatibility Notes ---------------------------------------------------------------------------------------------- * The minimum required versions for all `-linux-gnu` targets are now at least kernel 3.2 and glibc 2.17, for targets that previously supported older versions: [Increase the minimum linux-gnu versions](https://github.com/rust-lang/rust/pull/95026/) * [Network primitives are now implemented with the ideal Rust layout, not the C system layout](https://github.com/rust-lang/rust/pull/78802/) . This can cause problems when transmuting the types. * [Add assertion that `transmute_copy`’s `U` is not larger than `T`](https://github.com/rust-lang/rust/pull/98839/) * [A soundness bug in `BTreeMap` was fixed](https://github.com/rust-lang/rust/pull/99413/) that allowed data it was borrowing to be dropped before the container. * [The Drop behavior of C-like enums cast to ints has changed](https://github.com/rust-lang/rust/pull/96862/) . These are already discouraged by a compiler warning. * [Relate late-bound closure lifetimes to parent fn in NLL](https://github.com/rust-lang/rust/pull/98835/) * [Errors at const-eval time are now in future incompatibility reports](https://github.com/rust-lang/rust/pull/97743/) * On the `thumbv6m-none-eabi` target, some incorrect `asm!` statements were erroneously accepted if they used the high registers (r8 to r14) as an input/output operand. [This is no longer accepted](https://github.com/rust-lang/rust/pull/99155/) . * [`impl Trait` was accidentally accepted as the associated type value of return-position `impl Trait`](https://github.com/rust-lang/rust/pull/97346/) , without fulfilling all the trait bounds of that associated type, as long as the hidden type satisfies said bounds. This has been fixed. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-20) Internal Changes ---------------------------------------------------------------------------------------- These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. * Windows builds now use profile-guided optimization, providing 10-20% improvements to compiler performance: [Utilize PGO for windows x64 rustc dist builds](https://github.com/rust-lang/rust/pull/96978/) * [Stop keeping metadata in memory before writing it to disk](https://github.com/rust-lang/rust/pull/96544/) * [compiletest: strip debuginfo by default for mode=ui](https://github.com/rust-lang/rust/pull/98140/) * Many improvements to generated code for derives, including performance improvements: * [Don’t use match-destructuring for derived ops on structs.](https://github.com/rust-lang/rust/pull/98446/) * [Many small deriving cleanups](https://github.com/rust-lang/rust/pull/98741/) * [More derive output improvements](https://github.com/rust-lang/rust/pull/98758/) * [Clarify deriving code](https://github.com/rust-lang/rust/pull/98915/) * [Final derive output improvements](https://github.com/rust-lang/rust/pull/99046/) * [Stop injecting `#[allow(unused_qualifications)]` in generated `derive` implementations](https://github.com/rust-lang/rust/pull/99485/) * [Improve `derive(Debug)`](https://github.com/rust-lang/rust/pull/98190/) * [Bump to clap 3](https://github.com/rust-lang/rust/pull/98213/) * [fully move dropck to mir](https://github.com/rust-lang/rust/pull/98641/) * [Optimize `Vec::insert` for the case where `index == len`.](https://github.com/rust-lang/rust/pull/98755/) * [Convert rust-analyzer to an in-tree tool](https://github.com/rust-lang/rust/pull/99603/) [§](https://doc.rust-lang.org/stable/releases.html#version-1630-2022-08-11) Version 1.63.0 (2022-08-11) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-29) Language ------------------------------------------------------------------------ * [Remove migrate borrowck mode for pre-NLL errors.](https://github.com/rust-lang/rust/pull/95565/) * [Modify MIR building to drop repeat expressions with length zero.](https://github.com/rust-lang/rust/pull/95953/) * [Remove label/lifetime shadowing warnings.](https://github.com/rust-lang/rust/pull/96296/) * [Allow explicit generic arguments in the presence of `impl Trait` args.](https://github.com/rust-lang/rust/pull/96868/) * [Make `cenum_impl_drop_cast` warnings deny-by-default.](https://github.com/rust-lang/rust/pull/97652/) * [Prevent unwinding when `-C panic=abort` is used regardless of declared ABI.](https://github.com/rust-lang/rust/pull/96959/) * [lub: don’t bail out due to empty binders.](https://github.com/rust-lang/rust/pull/97867/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-29) Compiler ------------------------------------------------------------------------ * [Stabilize the `bundle` native library modifier,](https://github.com/rust-lang/rust/pull/95818/) also removing the deprecated `static-nobundle` linking kind. * [Add Apple WatchOS compile targets\*.](https://github.com/rust-lang/rust/pull/95243/) * [Add a Windows application manifest to rustc-main.](https://github.com/rust-lang/rust/pull/96737/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-29) Libraries -------------------------------------------------------------------------- * [Implement `Copy`, `Clone`, `PartialEq` and `Eq` for `core::fmt::Alignment`.](https://github.com/rust-lang/rust/pull/94530/) * [Extend `ptr::null` and `null_mut` to all thin (including extern) types.](https://github.com/rust-lang/rust/pull/94954/) * [`impl Read and Write for VecDeque`.](https://github.com/rust-lang/rust/pull/95632/) * [STD support for the Nintendo 3DS.](https://github.com/rust-lang/rust/pull/95897/) * [Use rounding in float to Duration conversion methods.](https://github.com/rust-lang/rust/pull/96051/) * [Make write/print macros eagerly drop temporaries.](https://github.com/rust-lang/rust/pull/96455/) * [Implement internal traits that enable `[OsStr]::join`.](https://github.com/rust-lang/rust/pull/96881/) * [Implement `Hash` for `core::alloc::Layout`.](https://github.com/rust-lang/rust/pull/97034/) * [Add capacity documentation for `OsString`.](https://github.com/rust-lang/rust/pull/97202/) * [Put a bound on collection misbehavior.](https://github.com/rust-lang/rust/pull/97316/) * [Make `std::mem::needs_drop` accept `?Sized`.](https://github.com/rust-lang/rust/pull/97675/) * [`impl Termination for Infallible` and then make the `Result` impls of `Termination` more generic.](https://github.com/rust-lang/rust/pull/97803/) * [Document Rust’s stance on `/proc/self/mem`.](https://github.com/rust-lang/rust/pull/97837/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-29) Stabilized APIs -------------------------------------------------------------------------------------- * [`array::from_fn`](https://doc.rust-lang.org/stable/std/array/fn.from_fn.html) * [`Box::into_pin`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.into_pin) * [`BinaryHeap::try_reserve`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_reserve) * [`BinaryHeap::try_reserve_exact`](https://doc.rust-lang.org/stable/alloc/collections/binary_heap/struct.BinaryHeap.html#method.try_reserve_exact) * [`OsString::try_reserve`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.try_reserve) * [`OsString::try_reserve_exact`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.try_reserve_exact) * [`PathBuf::try_reserve`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.try_reserve) * [`PathBuf::try_reserve_exact`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.try_reserve_exact) * [`Path::try_exists`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.try_exists) * [`Ref::filter_map`](https://doc.rust-lang.org/stable/std/cell/struct.Ref.html#method.filter_map) * [`RefMut::filter_map`](https://doc.rust-lang.org/stable/std/cell/struct.RefMut.html#method.filter_map) * [`NonNull::<[T]>::len`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.len) * [`ToOwned::clone_into`](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) * [`Ipv6Addr::to_ipv4_mapped`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.to_ipv4_mapped) * [`unix::io::AsFd`](https://doc.rust-lang.org/stable/std/os/unix/io/trait.AsFd.html) * [`unix::io::BorrowedFd<'fd>`](https://doc.rust-lang.org/stable/std/os/unix/io/struct.BorrowedFd.html) * [`unix::io::OwnedFd`](https://doc.rust-lang.org/stable/std/os/unix/io/struct.OwnedFd.html) * [`windows::io::AsHandle`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsHandle.html) * [`windows::io::BorrowedHandle<'handle>`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.BorrowedHandle.html) * [`windows::io::OwnedHandle`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedHandle.html) * [`windows::io::HandleOrInvalid`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.HandleOrInvalid.html) * [`windows::io::HandleOrNull`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.HandleOrNull.html) * [`windows::io::InvalidHandleError`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.InvalidHandleError.html) * [`windows::io::NullHandleError`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.NullHandleError.html) * [`windows::io::AsSocket`](https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html) * [`windows::io::BorrowedSocket<'handle>`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.BorrowedSocket.html) * [`windows::io::OwnedSocket`](https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedSocket.html) * [`thread::scope`](https://doc.rust-lang.org/stable/std/thread/fn.scope.html) * [`thread::Scope`](https://doc.rust-lang.org/stable/std/thread/fn.scope.html) * [`thread::ScopedJoinHandle`](https://doc.rust-lang.org/stable/std/thread/struct.ScopedJoinHandle.html) These APIs are now usable in const contexts: * [`array::from_ref`](https://doc.rust-lang.org/stable/std/array/fn.from_ref.html) * [`slice::from_ref`](https://doc.rust-lang.org/stable/std/slice/fn.from_ref.html) * [`intrinsics::copy`](https://doc.rust-lang.org/stable/std/intrinsics/fn.copy.html) * [`intrinsics::copy_nonoverlapping`](https://doc.rust-lang.org/stable/std/intrinsics/fn.copy_nonoverlapping.html) * [`<*const T>::copy_to`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to) * [`<*const T>::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to_nonoverlapping) * [`<*mut T>::copy_to`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to-1) * [`<*mut T>::copy_to_nonoverlapping`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_to_nonoverlapping-1) * [`<*mut T>::copy_from`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_from) * [`<*mut T>::copy_from_nonoverlapping`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.copy_from_nonoverlapping) * [`str::from_utf8`](https://doc.rust-lang.org/stable/std/str/fn.from_utf8.html) * [`Utf8Error::error_len`](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html#method.error_len) * [`Utf8Error::valid_up_to`](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html#method.valid_up_to) * [`Condvar::new`](https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.new) * [`Mutex::new`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html#method.new) * [`RwLock::new`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html#method.new) [§](https://doc.rust-lang.org/stable/releases.html#cargo-28) Cargo ------------------------------------------------------------------ * [Stabilize the `--config path` command-line argument.](https://github.com/rust-lang/cargo/pull/10755/) * [Expose rust-version in the environment as `CARGO_PKG_RUST_VERSION`.](https://github.com/rust-lang/cargo/pull/10713/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-28) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`#[link]` attributes are now checked more strictly,](https://github.com/rust-lang/rust/pull/96885/) which may introduce errors for invalid attribute arguments that were previously ignored. * [Rounding is now used when converting a float to a `Duration`.](https://github.com/rust-lang/rust/pull/96051/) The converted duration can differ slightly from what it was. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-21) Internal Changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Prepare Rust for LLVM opaque pointers.](https://github.com/rust-lang/rust/pull/94214/) [§](https://doc.rust-lang.org/stable/releases.html#version-1621-2022-07-19) Version 1.62.1 (2022-07-19) ======================================================================================================= Rust 1.62.1 addresses a few recent regressions in the compiler and standard library, and also mitigates a CPU vulnerability on Intel SGX. * [The compiler fixed unsound function coercions involving `impl Trait` return types.](https://github.com/rust-lang/rust/issues/98608) * [The compiler fixed an incremental compilation bug with `async fn` lifetimes.](https://github.com/rust-lang/rust/issues/98890) * [Windows added a fallback for overlapped I/O in synchronous reads and writes.](https://github.com/rust-lang/rust/pull/98950) * [The `x86_64-fortanix-unknown-sgx` target added a mitigation for the MMIO stale data vulnerability](https://github.com/rust-lang/rust/pull/98126) , advisory [INTEL-SA-00615](https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00615.html) . [§](https://doc.rust-lang.org/stable/releases.html#version-1620-2022-06-30) Version 1.62.0 (2022-06-30) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-30) Language ------------------------------------------------------------------------ * [Stabilize `#[derive(Default)]` on enums with a `#[default]` variant](https://github.com/rust-lang/rust/pull/94457/) * [Teach flow sensitive checks that visibly uninhabited call expressions never return](https://github.com/rust-lang/rust/pull/93313/) * [Fix constants not getting dropped if part of a diverging expression](https://github.com/rust-lang/rust/pull/94775/) * [Support unit struct/enum variant in destructuring assignment](https://github.com/rust-lang/rust/pull/95380/) * [Remove mutable\_borrow\_reservation\_conflict lint and allow the code pattern](https://github.com/rust-lang/rust/pull/96268/) * [`const` functions may now specify `extern "C"` or `extern "Rust"`](https://github.com/rust-lang/rust/pull/95346/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-30) Compiler ------------------------------------------------------------------------ * [linker: Stop using whole-archive on dependencies of dylibs](https://github.com/rust-lang/rust/pull/96436/) * [Make `unaligned_references` lint deny-by-default](https://github.com/rust-lang/rust/pull/95372/) This lint is also a future compatibility lint, and is expected to eventually become a hard error. * [Only add codegen backend to dep info if -Zbinary-dep-depinfo is used](https://github.com/rust-lang/rust/pull/93969/) * [Reject `#[thread_local]` attribute on non-static items](https://github.com/rust-lang/rust/pull/95006/) * [Add tier 3 `aarch64-pc-windows-gnullvm` and `x86_64-pc-windows-gnullvm` targets\*](https://github.com/rust-lang/rust/pull/94872/) * [Implement a lint to warn about unused macro rules](https://github.com/rust-lang/rust/pull/96150/) * [Promote `x86_64-unknown-none` target to Tier 2\*](https://github.com/rust-lang/rust/pull/95705/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-30) Libraries -------------------------------------------------------------------------- * [Windows: Use a pipe relay for chaining pipes](https://github.com/rust-lang/rust/pull/95841/) * [Replace Linux Mutex and Condvar with futex based ones.](https://github.com/rust-lang/rust/pull/95035/) * [Replace RwLock by a futex based one on Linux](https://github.com/rust-lang/rust/pull/95801/) * [std: directly use pthread in UNIX parker implementation](https://github.com/rust-lang/rust/pull/96393/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-30) Stabilized APIs -------------------------------------------------------------------------------------- * [`bool::then_some`](https://doc.rust-lang.org/stable/std/primitive.bool.html#method.then_some) * [`f32::total_cmp`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.total_cmp) * [`f64::total_cmp`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.total_cmp) * [`Stdin::lines`](https://doc.rust-lang.org/stable/std/io/struct.Stdin.html#method.lines) * [`windows::CommandExt::raw_arg`](https://doc.rust-lang.org/stable/std/os/windows/process/trait.CommandExt.html#tymethod.raw_arg) * [`impl Default for AssertUnwindSafe`](https://doc.rust-lang.org/stable/std/panic/struct.AssertUnwindSafe.html#impl-Default) * [`From> for Rc<[u8]>`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#impl-From%3CRc%3Cstr%3E%3E) * [`From> for Arc<[u8]>`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#impl-From%3CArc%3Cstr%3E%3E) * [`FusedIterator for EncodeWide`](https://doc.rust-lang.org/stable/std/os/windows/ffi/struct.EncodeWide.html#impl-FusedIterator) * [RDM intrinsics on aarch64](https://github.com/rust-lang/stdarch/pull/1285) [§](https://doc.rust-lang.org/stable/releases.html#clippy) Clippy ----------------------------------------------------------------- * [Create clippy lint against unexpectedly late drop for temporaries in match scrutinee expressions](https://github.com/rust-lang/rust/pull/94206/) [§](https://doc.rust-lang.org/stable/releases.html#cargo-29) Cargo ------------------------------------------------------------------ * Added the `cargo add` command for adding dependencies to `Cargo.toml` from the command-line. [docs](https://doc.rust-lang.org/nightly/cargo/commands/cargo-add.html) * Package ID specs now support `name@version` syntax in addition to the previous `name:version` to align with the behavior in `cargo add` and other tools. `cargo install` and `cargo yank` also now support this syntax so the version does not need to passed as a separate flag. * The `git` and `registry` directories in Cargo’s home directory (usually `~/.cargo`) are now marked as cache directories so that they are not included in backups or content indexing (on Windows). * Added automatic `@` argfile support, which will use “response files” if the command-line to `rustc` exceeds the operating system’s limit. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-29) Compatibility Notes ---------------------------------------------------------------------------------------------- * `cargo test` now passes `--target` to `rustdoc` if the specified target is the same as the host target. [#10594](https://github.com/rust-lang/cargo/pull/10594) * [rustdoc: doctests are now run on unexported `macro_rules!` macros, matching other private items](https://github.com/rust-lang/rust/pull/96630/) * [rustdoc: Remove .woff font files](https://github.com/rust-lang/rust/pull/96279/) * [Enforce Copy bounds for repeat elements while considering lifetimes](https://github.com/rust-lang/rust/pull/95819/) * [Windows: Fix potential unsoundness by aborting if `File` reads or writes cannot complete synchronously](https://github.com/rust-lang/rust/pull/95469/) . [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-22) Internal Changes ---------------------------------------------------------------------------------------- * [Unify ReentrantMutex implementations across all platforms](https://github.com/rust-lang/rust/pull/96042/) These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. [§](https://doc.rust-lang.org/stable/releases.html#version-1610-2022-05-19) Version 1.61.0 (2022-05-19) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-31) Language ------------------------------------------------------------------------ * [`const fn` signatures can now include generic trait bounds](https://github.com/rust-lang/rust/pull/93827/) * [`const fn` signatures can now use `impl Trait` in argument and return position](https://github.com/rust-lang/rust/pull/93827/) * [Function pointers can now be created, cast, and passed around in a `const fn`](https://github.com/rust-lang/rust/pull/93827/) * [Recursive calls can now set the value of a function’s opaque `impl Trait` return type](https://github.com/rust-lang/rust/pull/94081/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-31) Compiler ------------------------------------------------------------------------ * [Linking modifier syntax in `#[link]` attributes and on the command line, as well as the `whole-archive` modifier specifically, are now supported](https://github.com/rust-lang/rust/pull/93901/) * [The `char` type is now described as UTF-32 in debuginfo](https://github.com/rust-lang/rust/pull/89887/) * The [`#[target_feature]`](https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute) attribute [can now be used with aarch64 features](https://github.com/rust-lang/rust/pull/90621/) * X86 [`#[target_feature = "adx"]` is now stable](https://github.com/rust-lang/rust/pull/93745/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-31) Libraries -------------------------------------------------------------------------- * [`ManuallyDrop` is now documented to have the same layout as `T`](https://github.com/rust-lang/rust/pull/88375/) * [`#[ignore = "…"]` messages are printed when running tests](https://github.com/rust-lang/rust/pull/92714/) * [Consistently show absent stdio handles on Windows as NULL handles](https://github.com/rust-lang/rust/pull/93263/) * [Make `std::io::stdio::lock()` return `'static` handles.](https://github.com/rust-lang/rust/pull/93965/) Previously, the creation of locked handles to stdin/stdout/stderr would borrow the handles being locked, which prevented writing `let out = std::io::stdout().lock();` because `out` would outlive the return value of `stdout()`. Such code now works, eliminating a common pitfall that affected many Rust users. * [`Vec::from_raw_parts` is now less restrictive about its inputs](https://github.com/rust-lang/rust/pull/95016/) * [`std::thread::available_parallelism` now takes cgroup quotas into account.](https://github.com/rust-lang/rust/pull/92697/) Since `available_parallelism` is often used to create a thread pool for parallel computation, which may be CPU-bound for performance, `available_parallelism` will return a value consistent with the ability to use that many threads continuously, if possible. For instance, in a container with 8 virtual CPUs but quotas only allowing for 50% usage, `available_parallelism` will return 4. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-31) Stabilized APIs -------------------------------------------------------------------------------------- * [`Pin::static_mut`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.static_mut) * [`Pin::static_ref`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.static_ref) * [`Vec::retain_mut`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.retain_mut) * [`VecDeque::retain_mut`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.retain_mut) * [`Write` for `Cursor<[u8; N]>`](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html#impl-Write-4) * [`std::os::unix::net::SocketAddr::from_pathname`](https://doc.rust-lang.org/stable/std/os/unix/net/struct.SocketAddr.html#method.from_pathname) * [`std::process::ExitCode`](https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html) and [`std::process::Termination`](https://doc.rust-lang.org/stable/std/process/trait.Termination.html) . The stabilization of these two APIs now makes it possible for programs to return errors from `main` with custom exit codes. * [`std::thread::JoinHandle::is_finished`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.is_finished) These APIs are now usable in const contexts: * [`<*const T>::offset` and `<*mut T>::offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset) * [`<*const T>::wrapping_offset` and `<*mut T>::wrapping_offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_offset) * [`<*const T>::add` and `<*mut T>::add`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.add) * [`<*const T>::sub` and `<*mut T>::sub`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.sub) * [`<*const T>::wrapping_add` and `<*mut T>::wrapping_add`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_add) * [`<*const T>::wrapping_sub` and `<*mut T>::wrapping_sub`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_sub) * [`<[T]>::as_mut_ptr`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_ptr) * [`<[T]>::as_ptr_range`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_ptr_range) * [`<[T]>::as_mut_ptr_range`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_ptr_range) [§](https://doc.rust-lang.org/stable/releases.html#cargo-30) Cargo ------------------------------------------------------------------ No feature changes, but see compatibility notes. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-30) Compatibility Notes ---------------------------------------------------------------------------------------------- * Previously native static libraries were linked as `whole-archive` in some cases, but now rustc tries not to use `whole-archive` unless explicitly requested. This [change](https://github.com/rust-lang/rust/pull/93901/) may result in linking errors in some cases. To fix such errors, native libraries linked from the command line, build scripts, or [`#[link]` attributes](https://doc.rust-lang.org/stable/reference/items/external-blocks.html#the-link-attribute) need to * (more common) either be reordered to respect dependencies between them (if `a` depends on `b` then `a` should go first and `b` second) * (less common) or be updated to use the [`+whole-archive`](https://doc.rust-lang.org/stable/rustc/command-line-arguments.html#linking-modifiers-whole-archive) modifier. * [Catching a second unwind from FFI code while cleaning up from a Rust panic now causes the process to abort](https://github.com/rust-lang/rust/pull/92911/) * [Proc macros no longer see `ident` matchers wrapped in groups](https://github.com/rust-lang/rust/pull/92472/) * [The number of `#` in `r#` raw string literals is now required to be less than 256](https://github.com/rust-lang/rust/pull/95251/) * [When checking that a dyn type satisfies a trait bound, supertrait bounds are now enforced](https://github.com/rust-lang/rust/pull/92285/) * [`cargo vendor` now only accepts one value for each `--sync` flag](https://github.com/rust-lang/cargo/pull/10448/) * [`cfg` predicates in `all()` and `any()` are always evaluated to detect errors, instead of short-circuiting.](https://github.com/rust-lang/rust/pull/94295/) The compatibility considerations here arise in nightly-only code that used the short-circuiting behavior of `all` to write something like `cfg(all(feature = "nightly", syntax-requiring-nightly))`, which will now fail to compile. Instead, use either `cfg_attr(feature = "nightly", ...)` or nested uses of `cfg`. * [bootstrap: static-libstdcpp is now enabled by default, and can now be disabled when llvm-tools is enabled](https://github.com/rust-lang/rust/pull/94832/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-23) Internal Changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [debuginfo: Refactor debuginfo generation for types](https://github.com/rust-lang/rust/pull/94261/) * [Remove the everybody loops pass](https://github.com/rust-lang/rust/pull/93913/) [§](https://doc.rust-lang.org/stable/releases.html#version-1600-2022-04-07) Version 1.60.0 (2022-04-07) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-32) Language ------------------------------------------------------------------------ * [Stabilize `#[cfg(panic = "...")]` for either `"unwind"` or `"abort"`.](https://github.com/rust-lang/rust/pull/93658) * [Stabilize `#[cfg(target_has_atomic = "...")]` for each integer size and `"ptr"`.](https://github.com/rust-lang/rust/pull/93824) [§](https://doc.rust-lang.org/stable/releases.html#compiler-32) Compiler ------------------------------------------------------------------------ * [Enable combining `+crt-static` and `relocation-model=pic` on `x86_64-unknown-linux-gnu`](https://github.com/rust-lang/rust/pull/86374) * [Fixes wrong `unreachable_pub` lints on nested and glob public reexport](https://github.com/rust-lang/rust/pull/87487) * [Stabilize `-Z instrument-coverage` as `-C instrument-coverage`](https://github.com/rust-lang/rust/pull/90132) * [Stabilize `-Z print-link-args` as `--print link-args`](https://github.com/rust-lang/rust/pull/91606) * [Add new Tier 3 target `mips64-openwrt-linux-musl`\*](https://github.com/rust-lang/rust/pull/92300) * [Add new Tier 3 target `armv7-unknown-linux-uclibceabi` (softfloat)\*](https://github.com/rust-lang/rust/pull/92383) * [Fix invalid removal of newlines from doc comments](https://github.com/rust-lang/rust/pull/92357) * [Add kernel target for RustyHermit](https://github.com/rust-lang/rust/pull/92670) * [Deny mixing bin crate type with lib crate types](https://github.com/rust-lang/rust/pull/92933) * [Make rustc use `RUST_BACKTRACE=full` by default](https://github.com/rust-lang/rust/pull/93566) * [Upgrade to LLVM 14](https://github.com/rust-lang/rust/pull/93577) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-32) Libraries -------------------------------------------------------------------------- * [Guarantee call order for `sort_by_cached_key`](https://github.com/rust-lang/rust/pull/89621) * [Improve `Duration::try_from_secs_f32`/`f64` accuracy by directly processing exponent and mantissa](https://github.com/rust-lang/rust/pull/90247) * [Make `Instant::{duration_since, elapsed, sub}` saturating](https://github.com/rust-lang/rust/pull/89926) * [Remove non-monotonic clocks workarounds in `Instant::now`](https://github.com/rust-lang/rust/pull/89926) * [Make `BuildHasherDefault`, `iter::Empty` and `future::Pending` covariant](https://github.com/rust-lang/rust/pull/92630) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-32) Stabilized APIs -------------------------------------------------------------------------------------- * [`Arc::new_cyclic`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.new_cyclic) * [`Rc::new_cyclic`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.new_cyclic) * [`slice::EscapeAscii`](https://doc.rust-lang.org/stable/std/slice/struct.EscapeAscii.html) * [`<[u8]>::escape_ascii`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.escape_ascii) * [`u8::escape_ascii`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.escape_ascii) * [`Vec::spare_capacity_mut`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.spare_capacity_mut) * [`MaybeUninit::assume_init_drop`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_drop) * [`MaybeUninit::assume_init_read`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_read) * [`i8::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.abs_diff) * [`i16::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.abs_diff) * [`i32::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.abs_diff) * [`i64::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.abs_diff) * [`i128::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.abs_diff) * [`isize::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.abs_diff) * [`u8::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.abs_diff) * [`u16::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.abs_diff) * [`u32::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.abs_diff) * [`u64::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.abs_diff) * [`u128::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.abs_diff) * [`usize::abs_diff`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.abs_diff) * [`Display for io::ErrorKind`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Display) * [`From for ExitCode`](https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html#impl-From%3Cu8%3E) * [`Not for !` (the “never” type)](https://doc.rust-lang.org/stable/std/primitive.never.html#impl-Not) * [_Op_`Assign<$t> for Wrapping<$t>`](https://doc.rust-lang.org/stable/std/num/struct.Wrapping.html#trait-implementations) * [`arch::is_aarch64_feature_detected!`](https://doc.rust-lang.org/stable/std/arch/macro.is_aarch64_feature_detected.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-31) Cargo ------------------------------------------------------------------ * [Port cargo from `toml-rs` to `toml_edit`](https://github.com/rust-lang/cargo/pull/10086) * [Stabilize `-Ztimings` as `--timings`](https://github.com/rust-lang/cargo/pull/10245) * [Stabilize namespaced and weak dependency features.](https://github.com/rust-lang/cargo/pull/10269) * [Accept more `cargo:rustc-link-arg-*` types from build script output.](https://github.com/rust-lang/cargo/pull/10274) * [cargo-new should not add ignore rule on Cargo.lock inside subdirs](https://github.com/rust-lang/cargo/pull/10379) [§](https://doc.rust-lang.org/stable/releases.html#misc-7) Misc --------------------------------------------------------------- * [Ship docs on Tier 2 platforms by reusing the closest Tier 1 platform docs](https://github.com/rust-lang/rust/pull/92800) * [Drop rustc-docs from complete profile](https://github.com/rust-lang/rust/pull/93742) * [bootstrap: tidy up flag handling for llvm build](https://github.com/rust-lang/rust/pull/93918) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-31) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Remove compiler-rt linking hack on Android](https://github.com/rust-lang/rust/pull/83822) * [Mitigations for platforms with non-monotonic clocks have been removed from `Instant::now`](https://github.com/rust-lang/rust/pull/89926) . On platforms that don’t provide monotonic clocks, an instant is not guaranteed to be greater than an earlier instant anymore. * [`Instant::{duration_since, elapsed, sub}` do not panic anymore on underflow, saturating to `0` instead](https://github.com/rust-lang/rust/pull/89926) . In the real world the panic happened mostly on platforms with buggy monotonic clock implementations rather than catching programming errors like reversing the start and end times. Such programming errors will now results in `0` rather than a panic. * In a future release we’re planning to increase the baseline requirements for the Linux kernel to version 3.2, and for glibc to version 2.17. We’d love your feedback in [PR #95026](https://github.com/rust-lang/rust/pull/95026) . [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-24) Internal Changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Switch all libraries to the 2021 edition](https://github.com/rust-lang/rust/pull/92068) [§](https://doc.rust-lang.org/stable/releases.html#version-1590-2022-02-24) Version 1.59.0 (2022-02-24) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-33) Language ------------------------------------------------------------------------ * [Stabilize default arguments for const parameters and remove the ordering restriction for type and const parameters](https://github.com/rust-lang/rust/pull/90207/) * [Stabilize destructuring assignment](https://github.com/rust-lang/rust/pull/90521/) * [Relax private in public lint on generic bounds and where clauses of trait impls](https://github.com/rust-lang/rust/pull/90586/) * [Stabilize asm! and global\_asm! for x86, x86\_64, ARM, Aarch64, and RISC-V](https://github.com/rust-lang/rust/pull/91728/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-33) Compiler ------------------------------------------------------------------------ * [Stabilize new symbol mangling format, leaving it opt-in (-Csymbol-mangling-version=v0)](https://github.com/rust-lang/rust/pull/90128/) * [Emit LLVM optimization remarks when enabled with `-Cremark`](https://github.com/rust-lang/rust/pull/90833/) * [Fix sparc64 ABI for aggregates with floating point members](https://github.com/rust-lang/rust/pull/91003/) * [Warn when a `#[test]`\-like built-in attribute macro is present multiple times.](https://github.com/rust-lang/rust/pull/91172/) * [Add support for riscv64gc-unknown-freebsd](https://github.com/rust-lang/rust/pull/91284/) * [Stabilize `-Z emit-future-incompat` as `--json future-incompat`](https://github.com/rust-lang/rust/pull/91535/) * [Soft disable incremental compilation](https://github.com/rust-lang/rust/issues/94124) This release disables incremental compilation, unless the user has explicitly opted in via the newly added RUSTC\_FORCE\_INCREMENTAL=1 environment variable. This is due to a known and relatively frequently occurring bug in incremental compilation, which causes builds to issue internal compiler errors. This particular bug is already fixed on nightly, but that fix has not yet rolled out to stable and is deemed too risky for a direct stable backport. As always, we encourage users to test with nightly and report bugs so that we can track failures and fix issues earlier. See [94124](https://github.com/rust-lang/rust/issues/94124) for more details. [§](https://doc.rust-lang.org/stable/releases.html#libraries-33) Libraries -------------------------------------------------------------------------- * [Remove unnecessary bounds for some Hash{Map,Set} methods](https://github.com/rust-lang/rust/pull/91593/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-33) Stabilized APIs -------------------------------------------------------------------------------------- * [`std::thread::available_parallelism`](https://doc.rust-lang.org/stable/std/thread/fn.available_parallelism.html) * [`Result::copied`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.copied) * [`Result::cloned`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.cloned) * [`arch::asm!`](https://doc.rust-lang.org/stable/core/arch/macro.asm.html) * [`arch::global_asm!`](https://doc.rust-lang.org/stable/core/arch/macro.global_asm.html) * [`ops::ControlFlow::is_break`](https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html#method.is_break) * [`ops::ControlFlow::is_continue`](https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html#method.is_continue) * [`TryFrom for u8`](https://doc.rust-lang.org/stable/std/primitive.char.html#impl-TryFrom%3Cchar%3E) * [`char::TryFromCharError`](https://doc.rust-lang.org/stable/std/char/struct.TryFromCharError.html) implementing `Clone`, `Debug`, `Display`, `PartialEq`, `Copy`, `Eq`, `Error` * [`iter::zip`](https://doc.rust-lang.org/stable/std/iter/fn.zip.html) * [`NonZeroU8::is_power_of_two`](https://doc.rust-lang.org/stable/core/num/struct.NonZeroU8.html#method.is_power_of_two) * [`NonZeroU16::is_power_of_two`](https://doc.rust-lang.org/stable/core/num/struct.NonZeroU16.html#method.is_power_of_two) * [`NonZeroU32::is_power_of_two`](https://doc.rust-lang.org/stable/core/num/struct.NonZeroU32.html#method.is_power_of_two) * [`NonZeroU64::is_power_of_two`](https://doc.rust-lang.org/stable/core/num/struct.NonZeroU64.html#method.is_power_of_two) * [`NonZeroU128::is_power_of_two`](https://doc.rust-lang.org/stable/core/num/struct.NonZeroU128.html#method.is_power_of_two) * [`NonZeroUsize::is_power_of_two`](https://doc.rust-lang.org/stable/core/num/struct.NonZeroUsize.html#method.is_power_of_two) * [`DoubleEndedIterator for ToLowercase`](https://doc.rust-lang.org/stable/std/char/struct.ToLowercase.html#impl-DoubleEndedIterator) * [`DoubleEndedIterator for ToUppercase`](https://doc.rust-lang.org/stable/std/char/struct.ToUppercase.html#impl-DoubleEndedIterator) * [`TryFrom<&mut [T]> for [T; N]`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#impl-TryFrom%3C%26%27_%20mut%20%5BT%5D%3E) * [`UnwindSafe for Once`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#impl-UnwindSafe) * [`RefUnwindSafe for Once`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#impl-RefUnwindSafe) * [armv8 neon intrinsics for aarch64](https://github.com/rust-lang/stdarch/pull/1266) Const-stable: * [`mem::MaybeUninit::as_ptr`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.as_ptr) * [`mem::MaybeUninit::assume_init`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init) * [`mem::MaybeUninit::assume_init_ref`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_ref) * [`ffi::CStr::from_bytes_with_nul_unchecked`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.from_bytes_with_nul_unchecked) [§](https://doc.rust-lang.org/stable/releases.html#cargo-32) Cargo ------------------------------------------------------------------ * [Stabilize the `strip` profile option](https://github.com/rust-lang/cargo/pull/10088/) * [Stabilize future-incompat-report](https://github.com/rust-lang/cargo/pull/10165/) * [Support abbreviating `--release` as `-r`](https://github.com/rust-lang/cargo/pull/10133/) * [Support `term.quiet` configuration](https://github.com/rust-lang/cargo/pull/10152/) * [Remove `--host` from cargo {publish,search,login}](https://github.com/rust-lang/cargo/pull/10145/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-32) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Refactor weak symbols in std::sys::unix](https://github.com/rust-lang/rust/pull/90846/) This may add new, versioned, symbols when building with a newer glibc, as the standard library uses weak linkage rather than dynamically attempting to load certain symbols at runtime. * [Deprecate crate\_type and crate\_name nested inside `#![cfg_attr]`](https://github.com/rust-lang/rust/pull/83744/) This adds a future compatibility lint to supporting the use of cfg\_attr wrapping either crate\_type or crate\_name specification within Rust files; it is recommended that users migrate to setting the equivalent command line flags. * [Remove effect of `#[no_link]` attribute on name resolution](https://github.com/rust-lang/rust/pull/92034/) This may expose new names, leading to conflicts with preexisting names in a given namespace and a compilation failure. * [Cargo will document libraries before binaries.](https://github.com/rust-lang/cargo/pull/10172/) * [Respect doc=false in dependencies, not just the root crate](https://github.com/rust-lang/cargo/pull/10201/) * [Weaken guarantee around advancing underlying iterators in zip](https://github.com/rust-lang/rust/pull/83791/) * [Make split\_inclusive() on an empty slice yield an empty output](https://github.com/rust-lang/rust/pull/89825/) * [Update std::env::temp\_dir to use GetTempPath2 on Windows when available.](https://github.com/rust-lang/rust/pull/89999/) * [unreachable! was updated to match other formatting macro behavior on Rust 2021](https://github.com/rust-lang/rust/pull/92137/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-25) Internal Changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Fix many cases of normalization-related ICEs](https://github.com/rust-lang/rust/pull/91255/) * [Replace dominators algorithm with simple Lengauer-Tarjan](https://github.com/rust-lang/rust/pull/85013/) * [Store liveness in interval sets for region inference](https://github.com/rust-lang/rust/pull/90637/) * [Remove `in_band_lifetimes` from the compiler and standard library, in preparation for removing this unstable feature.](https://github.com/rust-lang/rust/issues/91867) [§](https://doc.rust-lang.org/stable/releases.html#version-1581-2022-01-20) Version 1.58.1 (2022-01-20) ======================================================================================================= * Fix race condition in `std::fs::remove_dir_all` ([CVE-2022-21658](https://www.cve.org/CVERecord?id=CVE-2022-21658) ) * [Handle captured arguments in the `useless_format` Clippy lint](https://github.com/rust-lang/rust-clippy/pull/8295) * [Move `non_send_fields_in_send_ty` Clippy lint to nursery](https://github.com/rust-lang/rust-clippy/pull/8075) * [Fix wrong error message displayed when some imports are missing](https://github.com/rust-lang/rust/pull/91254) * [Fix rustfmt not formatting generated files from stdin](https://github.com/rust-lang/rust/pull/92912) [§](https://doc.rust-lang.org/stable/releases.html#version-1580-2022-01-13) Version 1.58.0 (2022-01-13) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-34) Language ------------------------------------------------------------------------ * [Format strings can now capture arguments simply by writing `{ident}` in the string.](https://github.com/rust-lang/rust/pull/90473/) This works in all macros accepting format strings. Support for this in `panic!` (`panic!("{ident}")`) requires the 2021 edition; panic invocations in previous editions that appear to be trying to use this will result in a warning lint about not having the intended effect. * [`*const T` pointers can now be dereferenced in const contexts.](https://github.com/rust-lang/rust/pull/89551/) * [The rules for when a generic struct implements `Unsize` have been relaxed.](https://github.com/rust-lang/rust/pull/90417/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-34) Compiler ------------------------------------------------------------------------ * [Add LLVM CFI support to the Rust compiler](https://github.com/rust-lang/rust/pull/89652/) * [Stabilize -Z strip as -C strip](https://github.com/rust-lang/rust/pull/90058/) . Note that while release builds already don’t add debug symbols for the code you compile, the compiled standard library that ships with Rust includes debug symbols, so you may want to use the `strip` option to remove these symbols to produce smaller release binaries. Note that this release only includes support in rustc, not directly in cargo. * [Add support for LLVM coverage mapping format versions 5 and 6](https://github.com/rust-lang/rust/pull/91207/) * [Emit LLVM optimization remarks when enabled with `-Cremark`](https://github.com/rust-lang/rust/pull/90833/) * [Update the minimum external LLVM to 12](https://github.com/rust-lang/rust/pull/90175/) * [Add `x86_64-unknown-none` at Tier 3\*](https://github.com/rust-lang/rust/pull/89062/) * [Build musl dist artifacts with debuginfo enabled](https://github.com/rust-lang/rust/pull/90733/) . When building release binaries using musl, you may want to use the newly stabilized strip option to remove these debug symbols, reducing the size of your binaries. * [Don’t abort compilation after giving a lint error](https://github.com/rust-lang/rust/pull/87337/) * [Error messages point at the source of trait bound obligations in more places](https://github.com/rust-lang/rust/pull/89580/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-34) Libraries -------------------------------------------------------------------------- * [All remaining functions in the standard library have `#[must_use]` annotations where appropriate](https://github.com/rust-lang/rust/issues/89692/) , producing a warning when ignoring their return value. This helps catch mistakes such as expecting a function to mutate a value in place rather than return a new value. * [Paths are automatically canonicalized on Windows for operations that support it](https://github.com/rust-lang/rust/pull/89174/) * [Re-enable debug checks for `copy` and `copy_nonoverlapping`](https://github.com/rust-lang/rust/pull/90041/) * [Implement `RefUnwindSafe` for `Rc`](https://github.com/rust-lang/rust/pull/87467/) * [Make RSplit: Clone not require T: Clone](https://github.com/rust-lang/rust/pull/90117/) * [Implement `Termination` for `Result`](https://github.com/rust-lang/rust/pull/88601/) . This allows writing `fn main() -> Result`, for a program whose successful exits never involve returning from `main` (for instance, a program that calls `exit`, or that uses `exec` to run another program). [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-34) Stabilized APIs -------------------------------------------------------------------------------------- * [`Metadata::is_symlink`](https://doc.rust-lang.org/stable/std/fs/struct.Metadata.html#method.is_symlink) * [`Path::is_symlink`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.is_symlink) * [`{integer}::saturating_div`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.saturating_div) * [`Option::unwrap_unchecked`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_unchecked) * [`Result::unwrap_unchecked`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_unchecked) * [`Result::unwrap_err_unchecked`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_err_unchecked) * [`File::options`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.options) These APIs are now usable in const contexts: * [`Duration::new`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.new) * [`Duration::checked_add`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_add) * [`Duration::saturating_add`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_add) * [`Duration::checked_sub`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_sub) * [`Duration::saturating_sub`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_sub) * [`Duration::checked_mul`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_mul) * [`Duration::saturating_mul`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_mul) * [`Duration::checked_div`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_div) [§](https://doc.rust-lang.org/stable/releases.html#cargo-33) Cargo ------------------------------------------------------------------ * [Add –message-format for install command](https://github.com/rust-lang/cargo/pull/10107/) * [Warn when alias shadows external subcommand](https://github.com/rust-lang/cargo/pull/10082/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-19) Rustdoc ---------------------------------------------------------------------- * [Show all Deref implementations recursively in rustdoc](https://github.com/rust-lang/rust/pull/90183/) * [Use computed visibility in rustdoc](https://github.com/rust-lang/rust/pull/88447/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-33) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Try all stable method candidates first before trying unstable ones](https://github.com/rust-lang/rust/pull/90329/) . This change ensures that adding new nightly-only methods to the Rust standard library will not break code invoking methods of the same name from traits outside the standard library. * Windows: [`std::process::Command` will no longer search the current directory for executables.](https://github.com/rust-lang/rust/pull/87704/) * [All proc-macro backward-compatibility lints are now deny-by-default.](https://github.com/rust-lang/rust/pull/88041/) * [proc\_macro: Append .0 to unsuffixed float if it would otherwise become int token](https://github.com/rust-lang/rust/pull/90297/) * [Refactor weak symbols in std::sys::unix](https://github.com/rust-lang/rust/pull/90846/) . This optimizes accesses to glibc functions, by avoiding the use of dlopen. This does not increase the [minimum expected version of glibc](https://doc.rust-lang.org/nightly/rustc/platform-support.html) . However, software distributions that use symbol versions to detect library dependencies, and which take weak symbols into account in that analysis, may detect rust binaries as requiring newer versions of glibc. * [rustdoc now rejects some unexpected semicolons in doctests](https://github.com/rust-lang/rust/pull/91026/) [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-26) Internal Changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Implement coherence checks for negative trait impls](https://github.com/rust-lang/rust/pull/90104/) * [Add rustc lint, warning when iterating over hashmaps](https://github.com/rust-lang/rust/pull/89558/) * [Optimize live point computation](https://github.com/rust-lang/rust/pull/90491/) * [Enable verification for 1/32nd of queries loaded from disk](https://github.com/rust-lang/rust/pull/90361/) * [Implement version of normalize\_erasing\_regions that allows for normalization failure](https://github.com/rust-lang/rust/pull/91255/) [§](https://doc.rust-lang.org/stable/releases.html#version-1570-2021-12-02) Version 1.57.0 (2021-12-02) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-35) Language ------------------------------------------------------------------------ * [Macro attributes may follow `#[derive]` and will see the original (pre-`cfg`) input.](https://github.com/rust-lang/rust/pull/87220/) * [Accept curly-brace macros in expressions, like `m!{ .. }.method()` and `m!{ .. }?`.](https://github.com/rust-lang/rust/pull/88690/) * [Allow panicking in constant evaluation.](https://github.com/rust-lang/rust/pull/89508/) * [Ignore derived `Clone` and `Debug` implementations during dead code analysis.](https://github.com/rust-lang/rust/pull/85200/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-35) Compiler ------------------------------------------------------------------------ * [Create more accurate debuginfo for vtables.](https://github.com/rust-lang/rust/pull/89597/) * [Add `armv6k-nintendo-3ds` at Tier 3\*.](https://github.com/rust-lang/rust/pull/88529/) * [Add `armv7-unknown-linux-uclibceabihf` at Tier 3\*.](https://github.com/rust-lang/rust/pull/88952/) * [Add `m68k-unknown-linux-gnu` at Tier 3\*.](https://github.com/rust-lang/rust/pull/88321/) * [Add SOLID targets at Tier 3\*:](https://github.com/rust-lang/rust/pull/86191/) `aarch64-kmc-solid_asp3`, `armv7a-kmc-solid_asp3-eabi`, `armv7a-kmc-solid_asp3-eabihf` \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-35) Libraries -------------------------------------------------------------------------- * [Avoid allocations and copying in `Vec::leak`](https://github.com/rust-lang/rust/pull/89337/) * [Add `#[repr(i8)]` to `Ordering`](https://github.com/rust-lang/rust/pull/89507/) * [Optimize `File::read_to_end` and `read_to_string`](https://github.com/rust-lang/rust/pull/89582/) * [Update to Unicode 14.0](https://github.com/rust-lang/rust/pull/89614/) * [Many more functions are marked `#[must_use]`](https://github.com/rust-lang/rust/issues/89692/) , producing a warning when ignoring their return value. This helps catch mistakes such as expecting a function to mutate a value in place rather than return a new value. [§](https://doc.rust-lang.org/stable/releases.html#stabilised-apis) Stabilised APIs ----------------------------------------------------------------------------------- * [`[T; N]::as_mut_slice`](https://doc.rust-lang.org/std/primitive.array.html#method.as_mut_slice) * [`[T; N]::as_slice`](https://doc.rust-lang.org/std/primitive.array.html#method.as_slice) * [`collections::TryReserveError`](https://doc.rust-lang.org/std/collections/struct.TryReserveError.html) * [`HashMap::try_reserve`](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.try_reserve) * [`HashSet::try_reserve`](https://doc.rust-lang.org/std/collections/hash_set/struct.HashSet.html#method.try_reserve) * [`String::try_reserve`](https://doc.rust-lang.org/alloc/string/struct.String.html#method.try_reserve) * [`String::try_reserve_exact`](https://doc.rust-lang.org/alloc/string/struct.String.html#method.try_reserve_exact) * [`Vec::try_reserve`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.try_reserve) * [`Vec::try_reserve_exact`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.try_reserve_exact) * [`VecDeque::try_reserve`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.try_reserve) * [`VecDeque::try_reserve_exact`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.try_reserve_exact) * [`Iterator::map_while`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map_while) * [`iter::MapWhile`](https://doc.rust-lang.org/std/iter/struct.MapWhile.html) * [`proc_macro::is_available`](https://doc.rust-lang.org/proc_macro/fn.is_available.html) * [`Command::get_program`](https://doc.rust-lang.org/std/process/struct.Command.html#method.get_program) * [`Command::get_args`](https://doc.rust-lang.org/std/process/struct.Command.html#method.get_args) * [`Command::get_envs`](https://doc.rust-lang.org/std/process/struct.Command.html#method.get_envs) * [`Command::get_current_dir`](https://doc.rust-lang.org/std/process/struct.Command.html#method.get_current_dir) * [`CommandArgs`](https://doc.rust-lang.org/std/process/struct.CommandArgs.html) * [`CommandEnvs`](https://doc.rust-lang.org/std/process/struct.CommandEnvs.html) These APIs are now usable in const contexts: * [`hint::unreachable_unchecked`](https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-34) Cargo ------------------------------------------------------------------ * [Stabilize custom profiles](https://github.com/rust-lang/cargo/pull/9943/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-34) Compatibility notes ---------------------------------------------------------------------------------------------- * [Ignore derived `Clone` and `Debug` implementations during dead code analysis.](https://github.com/rust-lang/rust/pull/85200/) This will break some builds that set `#![deny(dead_code)]`. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-27) Internal changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Added an experimental backend for codegen with `libgccjit`.](https://github.com/rust-lang/rust/pull/87260/) [§](https://doc.rust-lang.org/stable/releases.html#version-1561-2021-11-01) Version 1.56.1 (2021-11-01) ======================================================================================================= * New lints to detect the presence of bidirectional-override Unicode codepoints in the compiled source code ([CVE-2021-42574](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-42574) ) [§](https://doc.rust-lang.org/stable/releases.html#version-1560-2021-10-21) Version 1.56.0 (2021-10-21) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-36) Language ------------------------------------------------------------------------ * [The 2021 Edition is now stable.](https://github.com/rust-lang/rust/pull/88100) See [the edition guide](https://doc.rust-lang.org/nightly/edition-guide/rust-2021/index.html) for more details. * [The pattern in `binding @ pattern` can now also introduce new bindings.](https://github.com/rust-lang/rust/pull/85305) * [Union field access is permitted in `const fn`.](https://github.com/rust-lang/rust/pull/85769#issuecomment-854363720) [§](https://doc.rust-lang.org/stable/releases.html#compiler-36) Compiler ------------------------------------------------------------------------ * [Upgrade to LLVM 13.](https://github.com/rust-lang/rust/pull/87570) * [Support memory, address, and thread sanitizers on aarch64-unknown-freebsd.](https://github.com/rust-lang/rust/pull/88023) * [Allow specifying a deployment target version for all iOS targets](https://github.com/rust-lang/rust/pull/87699) * [Warnings can be forced on with `--force-warn`.](https://github.com/rust-lang/rust/pull/87472) This feature is primarily intended for usage by `cargo fix`, rather than end users. * [Promote `aarch64-apple-ios-sim` to Tier 2\*.](https://github.com/rust-lang/rust/pull/87760) * [Add `powerpc-unknown-freebsd` at Tier 3\*.](https://github.com/rust-lang/rust/pull/87370) * [Add `riscv32imc-esp-espidf` at Tier 3\*.](https://github.com/rust-lang/rust/pull/87666) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-36) Libraries -------------------------------------------------------------------------- * [Allow writing of incomplete UTF-8 sequences via stdout/stderr on Windows.](https://github.com/rust-lang/rust/pull/83342) The Windows console still requires valid Unicode, but this change allows splitting a UTF-8 character across multiple write calls. This allows, for instance, programs that just read and write data buffers (e.g. copying a file to stdout) without regard for Unicode or character boundaries. * [Prefer `AtomicU{64,128}` over Mutex for Instant backsliding protection.](https://github.com/rust-lang/rust/pull/83093) For this use case, atomics scale much better under contention. * [Implement `Extend<(A, B)>` for `(Extend, Extend)`](https://github.com/rust-lang/rust/pull/85835) * [impl Default, Copy, Clone for std::io::Sink and std::io::Empty](https://github.com/rust-lang/rust/pull/86744) * [`impl From<[(K, V); N]>` for all collections.](https://github.com/rust-lang/rust/pull/84111) * [Remove `P: Unpin` bound on impl Future for Pin.](https://github.com/rust-lang/rust/pull/81363) * [Treat invalid environment variable names as nonexistent.](https://github.com/rust-lang/rust/pull/86183) Previously, the environment functions would panic if given a variable name with an internal null character or equal sign (`=`). Now, these functions will just treat such names as nonexistent variables, since the OS cannot represent the existence of a variable with such a name. [§](https://doc.rust-lang.org/stable/releases.html#stabilised-apis-1) Stabilised APIs ------------------------------------------------------------------------------------- * [`std::os::unix::fs::chroot`](https://doc.rust-lang.org/stable/std/os/unix/fs/fn.chroot.html) * [`UnsafeCell::raw_get`](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html#method.raw_get) * [`BufWriter::into_parts`](https://doc.rust-lang.org/stable/std/io/struct.BufWriter.html#method.into_parts) * [`core::panic::{UnwindSafe, RefUnwindSafe, AssertUnwindSafe}`](https://github.com/rust-lang/rust/pull/84662) These APIs were previously stable in `std`, but are now also available in `core`. * [`Vec::shrink_to`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.shrink_to) * [`String::shrink_to`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.shrink_to) * [`OsString::shrink_to`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.shrink_to) * [`PathBuf::shrink_to`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.shrink_to) * [`BinaryHeap::shrink_to`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.shrink_to) * [`VecDeque::shrink_to`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.shrink_to) * [`HashMap::shrink_to`](https://doc.rust-lang.org/stable/std/collections/hash_map/struct.HashMap.html#method.shrink_to) * [`HashSet::shrink_to`](https://doc.rust-lang.org/stable/std/collections/hash_set/struct.HashSet.html#method.shrink_to) These APIs are now usable in const contexts: * [`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html) * [`[T]::first`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.first) * [`[T]::split_first`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first) * [`[T]::last`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.last) * [`[T]::split_last`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last) [§](https://doc.rust-lang.org/stable/releases.html#cargo-35) Cargo ------------------------------------------------------------------ * [Cargo supports specifying a minimum supported Rust version in Cargo.toml.](https://doc.rust-lang.org/nightly/cargo/reference/manifest.html#the-rust-version-field) This has no effect at present on dependency version selection. We encourage crates to specify their minimum supported Rust version, and we encourage CI systems that support Rust code to include a crate’s specified minimum version in the test matrix for that crate by default. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-35) Compatibility notes ---------------------------------------------------------------------------------------------- * [Update to new argument parsing rules on Windows.](https://github.com/rust-lang/rust/pull/87580) This adjusts Rust’s standard library to match the behavior of the standard libraries for C/C++. The rules have changed slightly over time, and this PR brings us to the latest set of rules (changed in 2008). * [Disallow the aapcs calling convention on aarch64](https://github.com/rust-lang/rust/pull/88399) This was already not supported by LLVM; this change surfaces this lack of support with a better error message. * [Make `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` warn by default](https://github.com/rust-lang/rust/pull/87385) * [Warn when an escaped newline skips multiple lines.](https://github.com/rust-lang/rust/pull/87671) * [Calls to `libc::getpid` / `std::process::id` from `Command::pre_exec` may return different values on glibc <= 2.24.](https://github.com/rust-lang/rust/pull/81825#issuecomment-808406918) Rust now invokes the `clone3` system call directly, when available, to use new functionality available via that system call. Older versions of glibc cache the result of `getpid`, and only update that cache when calling glibc’s clone/fork functions, so a direct system call bypasses that cache update. glibc 2.25 and newer no longer cache `getpid` for exactly this reason. [§](https://doc.rust-lang.org/stable/releases.html#internal-changes-28) Internal changes ---------------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [LLVM is compiled with PGO in published x86\_64-unknown-linux-gnu artifacts.](https://github.com/rust-lang/rust/pull/88069) This improves the performance of most Rust builds. * [Unify representation of macros in internal data structures.](https://github.com/rust-lang/rust/pull/88019) This change fixes a host of bugs with the handling of macros by the compiler, as well as rustdoc. [§](https://doc.rust-lang.org/stable/releases.html#version-1550-2021-09-09) Version 1.55.0 (2021-09-09) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-37) Language ------------------------------------------------------------------------ * [You can now write open “from” range patterns (`X..`), which will start at `X` and will end at the maximum value of the integer.](https://github.com/rust-lang/rust/pull/83918) * [You can now explicitly import the prelude of different editions through `std::prelude` (e.g. `use std::prelude::rust_2021::*;`).](https://github.com/rust-lang/rust/pull/86294) [§](https://doc.rust-lang.org/stable/releases.html#compiler-37) Compiler ------------------------------------------------------------------------ * [Added tier 3\* support for `powerpc64le-unknown-freebsd`.](https://github.com/rust-lang/rust/pull/83572) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-37) Libraries -------------------------------------------------------------------------- * [Updated std’s float parsing to use the Eisel-Lemire algorithm.](https://github.com/rust-lang/rust/pull/86761) These improvements should in general provide faster string parsing of floats, no longer reject certain valid floating point values, and reduce the produced code size for non-stripped artifacts. * [`string::Drain` now implements `AsRef` and `AsRef<[u8]>`.](https://github.com/rust-lang/rust/pull/86858) [§](https://doc.rust-lang.org/stable/releases.html#stabilised-apis-2) Stabilised APIs ------------------------------------------------------------------------------------- * [`Bound::cloned`](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html#method.cloned) * [`Drain::as_str`](https://doc.rust-lang.org/stable/std/string/struct.Drain.html#method.as_str) * [`IntoInnerError::into_error`](https://doc.rust-lang.org/stable/std/io/struct.IntoInnerError.html#method.into_error) * [`IntoInnerError::into_parts`](https://doc.rust-lang.org/stable/std/io/struct.IntoInnerError.html#method.into_parts) * [`MaybeUninit::assume_init_mut`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_mut) * [`MaybeUninit::assume_init_ref`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.assume_init_ref) * [`MaybeUninit::write`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.write) * [`array::map`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.map) * [`ops::ControlFlow`](https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html) * [`x86::_bittest`](https://doc.rust-lang.org/stable/core/arch/x86/fn._bittest.html) * [`x86::_bittestandcomplement`](https://doc.rust-lang.org/stable/core/arch/x86/fn._bittestandcomplement.html) * [`x86::_bittestandreset`](https://doc.rust-lang.org/stable/core/arch/x86/fn._bittestandreset.html) * [`x86::_bittestandset`](https://doc.rust-lang.org/stable/core/arch/x86/fn._bittestandset.html) * [`x86_64::_bittest64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittest64.html) * [`x86_64::_bittestandcomplement64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittestandcomplement64.html) * [`x86_64::_bittestandreset64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittestandreset64.html) * [`x86_64::_bittestandset64`](https://doc.rust-lang.org/stable/core/arch/x86_64/fn._bittestandset64.html) The following previously stable functions are now `const`. * [`str::from_utf8_unchecked`](https://doc.rust-lang.org/stable/std/str/fn.from_utf8_unchecked.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-36) Cargo ------------------------------------------------------------------ * [Cargo will now deduplicate compiler diagnostics to the terminal when invoking rustc in parallel such as when using `cargo test`.](https://github.com/rust-lang/cargo/pull/9675) * [The package definition in `cargo metadata` now includes the `"default_run"` field from the manifest.](https://github.com/rust-lang/cargo/pull/9550) * [Added `cargo d` as an alias for `cargo doc`.](https://github.com/rust-lang/cargo/pull/9680) * [Added `{lib}` as formatting option for `cargo tree` to print the `"lib_name"` of packages.](https://github.com/rust-lang/cargo/pull/9663) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-20) Rustdoc ---------------------------------------------------------------------- * [Added “Go to item on exact match” search option.](https://github.com/rust-lang/rust/pull/85876) * [The “Implementors” section on traits no longer shows redundant method definitions.](https://github.com/rust-lang/rust/pull/85970) * [Trait implementations are toggled open by default.](https://github.com/rust-lang/rust/pull/86260) This should make the implementations more searchable by tools like `CTRL+F` in your browser. * [Intra-doc links should now correctly resolve associated items (e.g. methods) through type aliases.](https://github.com/rust-lang/rust/pull/86334) * [Traits which are marked with `#[doc(hidden)]` will no longer appear in the “Trait Implementations” section.](https://github.com/rust-lang/rust/pull/86513) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-36) Compatibility Notes ---------------------------------------------------------------------------------------------- * [std functions that return an `io::Error` will no longer use the `ErrorKind::Other` variant.](https://github.com/rust-lang/rust/pull/85746) This is to better reflect that these kinds of errors could be categorised [into newer more specific `ErrorKind` variants](https://github.com/rust-lang/rust/pull/79965) , and that they do not represent a user error. * [Using environment variable names with `process::Command` on Windows now behaves as expected.](https://github.com/rust-lang/rust/pull/85270) Previously using environment variables with `Command` would cause them to be ASCII-uppercased. * [Rustdoc will now warn on using rustdoc lints that aren’t prefixed with `rustdoc::`](https://github.com/rust-lang/rust/pull/86849) * `RUSTFLAGS` is no longer set for build scripts. Build scripts should use `CARGO_ENCODED_RUSTFLAGS` instead. See the [documentation](https://doc.rust-lang.org/nightly/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts) for more details. [§](https://doc.rust-lang.org/stable/releases.html#version-1540-2021-07-29) Version 1.54.0 (2021-07-29) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-38) Language ------------------------------------------------------------------------ * [You can now use macros for values in some built-in attributes.](https://github.com/rust-lang/rust/pull/83366) This primarily allows you to call macros within the `#[doc]` attribute. For example, to include external documentation in your crate, you can now write the following: #![doc = include_str!("README.md")] [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bdoc+=+include_str!(%22README.md%22)%5D%0Afn+main()+%7B%0A%0A%7D&edition=2015 "Run code") * [You can now cast between unsized slice types (and types which contain unsized slices) in `const fn`.](https://github.com/rust-lang/rust/pull/85078) * [You can now use multiple generic lifetimes with `impl Trait` where the lifetimes don’t explicitly outlive another.](https://github.com/rust-lang/rust/pull/84701) In code this means that you can now have `impl Trait<'a, 'b>` where as before you could only have `impl Trait<'a, 'b> where 'b: 'a`. [§](https://doc.rust-lang.org/stable/releases.html#compiler-38) Compiler ------------------------------------------------------------------------ * [Rustc will now search for custom JSON targets in `/lib/rustlib//target.json` where `/` is the “sysroot” directory.](https://github.com/rust-lang/rust/pull/83800) You can find your sysroot directory by running `rustc --print sysroot`. * [Added `wasm` as a `target_family` for WebAssembly platforms.](https://github.com/rust-lang/rust/pull/84072) * [You can now use `#[target_feature]` on safe functions when targeting WebAssembly platforms.](https://github.com/rust-lang/rust/pull/84988) * [Improved debugger output for enums on Windows MSVC platforms.](https://github.com/rust-lang/rust/pull/85292) * [Added tier 3\* support for `bpfel-unknown-none` and `bpfeb-unknown-none`.](https://github.com/rust-lang/rust/pull/79608) * [`-Zmutable-noalias=yes`](https://github.com/rust-lang/rust/pull/82834) is enabled by default when using LLVM 12 or above. \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-38) Libraries -------------------------------------------------------------------------- * [`panic::panic_any` will now `#[track_caller]`.](https://github.com/rust-lang/rust/pull/85745) * [Added `OutOfMemory` as a variant of `io::ErrorKind`.](https://github.com/rust-lang/rust/pull/84744) * [`proc_macro::Literal` now implements `FromStr`.](https://github.com/rust-lang/rust/pull/84717) * [The implementations of vendor intrinsics in core::arch have been significantly refactored.](https://github.com/rust-lang/rust/pull/83278) The main user-visible changes are a 50% reduction in the size of libcore.rlib and stricter validation of constant operands passed to intrinsics. The latter is technically a breaking change, but allows Rust to more closely match the C vendor intrinsics API. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-35) Stabilized APIs -------------------------------------------------------------------------------------- * [`BTreeMap::into_keys`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_keys) * [`BTreeMap::into_values`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_values) * [`HashMap::into_keys`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_keys) * [`HashMap::into_values`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_values) * [`arch::wasm32`](https://doc.rust-lang.org/core/arch/wasm32/index.html) * [`VecDeque::binary_search`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search) * [`VecDeque::binary_search_by`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by) * [`VecDeque::binary_search_by_key`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by_key) * [`VecDeque::partition_point`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.partition_point) [§](https://doc.rust-lang.org/stable/releases.html#cargo-37) Cargo ------------------------------------------------------------------ * [Added the `--prune ` option to `cargo-tree` to remove a package from the dependency graph.](https://github.com/rust-lang/cargo/pull/9520) * [Added the `--depth` option to `cargo-tree` to print only to a certain depth in the tree](https://github.com/rust-lang/cargo/pull/9499) * [Added the `no-proc-macro` value to `cargo-tree --edges` to hide procedural macro dependencies.](https://github.com/rust-lang/cargo/pull/9488) * [A new environment variable named `CARGO_TARGET_TMPDIR` is available.](https://github.com/rust-lang/cargo/pull/9375) This variable points to a directory that integration tests and benches can use as a “scratchpad” for testing filesystem operations. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-37) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Mixing Option and Result via `?` is no longer permitted in closures for inferred types.](https://github.com/rust-lang/rust/issues/86831) * [Previously unsound code is no longer permitted where different constructors in branches could require different lifetimes.](https://github.com/rust-lang/rust/issues/85574) * As previously mentioned the [`std::arch` intrinsics now uses stricter const checking](https://github.com/rust-lang/rust/pull/83278) than before and may reject some previously accepted code. * [`i128` multiplication on Cortex M0+ platforms currently unconditionally causes overflow when compiled with `codegen-units = 1`.](https://github.com/rust-lang/rust/issues/86063) [§](https://doc.rust-lang.org/stable/releases.html#version-1530-2021-06-17) Version 1.53.0 (2021-06-17) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-39) Language ------------------------------------------------------------------------ * [You can now use unicode for identifiers.](https://github.com/rust-lang/rust/pull/83799) This allows multilingual identifiers but still doesn’t allow glyphs that are not considered characters such as `◆` or `🦀`. More specifically you can now use any identifier that matches the UAX #31 “Unicode Identifier and Pattern Syntax” standard. This is the same standard as languages like Python, however Rust uses NFC normalization which may be different from other languages. * [You can now specify “or patterns” inside pattern matches.](https://github.com/rust-lang/rust/pull/79278) Previously you could only use `|` (OR) on complete patterns. E.g. let x = Some(2u8); // Before matches!(x, Some(1) | Some(2)); // Now matches!(x, Some(1 | 2)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+x+=+Some(2u8);%0A++++//+Before%0A++++matches!(x,+Some(1)+%7C+Some(2));%0A++++//+Now%0A++++matches!(x,+Some(1+%7C+2));%0A%7D&edition=2015 "Run code") * [Added the `:pat_param` `macro_rules!` matcher.](https://github.com/rust-lang/rust/pull/83386) This matcher has the same semantics as the `:pat` matcher. This is to allow `:pat` to change semantics to being a pattern fragment in a future edition. [§](https://doc.rust-lang.org/stable/releases.html#compiler-39) Compiler ------------------------------------------------------------------------ * [Updated the minimum external LLVM version to LLVM 10.](https://github.com/rust-lang/rust/pull/83387) * [Added Tier 3\* support for the `wasm64-unknown-unknown` target.](https://github.com/rust-lang/rust/pull/80525) * [Improved debuginfo for closures and async functions on Windows MSVC.](https://github.com/rust-lang/rust/pull/83941) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-39) Libraries -------------------------------------------------------------------------- * [Abort messages will now forward to `android_set_abort_message` on Android platforms when available.](https://github.com/rust-lang/rust/pull/81469) * [`slice::IterMut<'_, T>` now implements `AsRef<[T]>`](https://github.com/rust-lang/rust/pull/82771) * [Arrays of any length now implement `IntoIterator`.](https://github.com/rust-lang/rust/pull/84147) Currently calling `.into_iter()` as a method on an array will return `impl Iterator`, but this may change in a future edition to change `Item` to `T`. Calling `IntoIterator::into_iter` directly on arrays will provide `impl Iterator` as expected. * [`leading_zeros`, and `trailing_zeros` are now available on all `NonZero` integer types.](https://github.com/rust-lang/rust/pull/84082) * [`{f32, f64}::from_str` now parse and print special values (`NaN`, `-0`) according to IEEE 754.](https://github.com/rust-lang/rust/pull/78618) * [You can now index into slices using `(Bound, Bound)`.](https://github.com/rust-lang/rust/pull/77704) * [Add the `BITS` associated constant to all numeric types.](https://github.com/rust-lang/rust/pull/82565) [§](https://doc.rust-lang.org/stable/releases.html#stabilised-apis-3) Stabilised APIs ------------------------------------------------------------------------------------- * [`AtomicBool::fetch_update`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.fetch_update) * [`AtomicPtr::fetch_update`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicPtr.html#method.fetch_update) * [`BTreeMap::retain`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.retain) * [`BTreeSet::retain`](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.retain) * [`BufReader::seek_relative`](https://doc.rust-lang.org/std/io/struct.BufReader.html#method.seek_relative) * [`DebugStruct::non_exhaustive`](https://doc.rust-lang.org/std/fmt/struct.DebugStruct.html#method.finish_non_exhaustive) * [`Duration::MAX`](https://doc.rust-lang.org/std/time/struct.Duration.html#associatedconstant.MAX) * [`Duration::ZERO`](https://doc.rust-lang.org/std/time/struct.Duration.html#associatedconstant.ZERO) * [`Duration::is_zero`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.is_zero) * [`Duration::saturating_add`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_add) * [`Duration::saturating_mul`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_mul) * [`Duration::saturating_sub`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.saturating_sub) * [`ErrorKind::Unsupported`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.Unsupported) * [`Option::insert`](https://doc.rust-lang.org/std/option/enum.Option.html#method.insert) * [`Ordering::is_eq`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_eq) * [`Ordering::is_ge`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_ge) * [`Ordering::is_gt`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_gt) * [`Ordering::is_le`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_le) * [`Ordering::is_lt`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_lt) * [`Ordering::is_ne`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.is_ne) * [`OsStr::is_ascii`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.is_ascii) * [`OsStr::make_ascii_lowercase`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.make_ascii_lowercase) * [`OsStr::make_ascii_uppercase`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.make_ascii_uppercase) * [`OsStr::to_ascii_lowercase`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_ascii_lowercase) * [`OsStr::to_ascii_uppercase`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_ascii_uppercase) * [`Peekable::peek_mut`](https://doc.rust-lang.org/std/iter/struct.Peekable.html#method.peek_mut) * [`Rc::decrement_strong_count`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.decrement_strong_count) * [`Rc::increment_strong_count`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.increment_strong_count) * [`Vec::extend_from_within`](https://doc.rust-lang.org/beta/std/vec/struct.Vec.html#method.extend_from_within) * [`array::from_mut`](https://doc.rust-lang.org/beta/std/array/fn.from_mut.html) * [`array::from_ref`](https://doc.rust-lang.org/stable/std/array/fn.from_ref.html) * [`cmp::max_by_key`](https://doc.rust-lang.org/beta/std/cmp/fn.max_by_key.html) * [`cmp::max_by`](https://doc.rust-lang.org/beta/std/cmp/fn.max_by.html) * [`cmp::min_by_key`](https://doc.rust-lang.org/beta/std/cmp/fn.min_by_key.html) * [`cmp::min_by`](https://doc.rust-lang.org/beta/std/cmp/fn.min_by.html) * [`f32::is_subnormal`](https://doc.rust-lang.org/std/primitive.f32.html#method.is_subnormal) * [`f64::is_subnormal`](https://doc.rust-lang.org/std/primitive.f64.html#method.is_subnormal) [§](https://doc.rust-lang.org/stable/releases.html#cargo-38) Cargo ------------------------------------------------------------------ * [Cargo now supports git repositories where the default `HEAD` branch is not “master”.](https://github.com/rust-lang/cargo/pull/9392) This also includes a switch to the version 3 `Cargo.lock` format which can handle default branches correctly. * [macOS targets now default to `unpacked` split-debuginfo.](https://github.com/rust-lang/cargo/pull/9298) * [The `authors` field is no longer included in `Cargo.toml` for new projects.](https://github.com/rust-lang/cargo/pull/9282) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-21) Rustdoc ---------------------------------------------------------------------- * [Added the `rustdoc::bare_urls` lint that warns when you have URLs without hyperlinks.](https://github.com/rust-lang/rust/pull/81764) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-38) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Implement token-based handling of attributes during expansion](https://github.com/rust-lang/rust/pull/82608) * [`Ipv4::from_str` will now reject octal format IP addresses in addition to rejecting hexadecimal IP addresses.](https://github.com/rust-lang/rust/pull/83652) The octal format can lead to confusion and potential security vulnerabilities and [is no longer recommended](https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1) . * [The added `BITS` constant may conflict with external definitions.](https://github.com/rust-lang/rust/pull/85667) In particular, this was known to be a problem in the `lexical-core` crate, but they have published fixes for semantic versions 0.4 through 0.7. To update this dependency alone, use `cargo update -p lexical-core`. * Incremental compilation remains off by default, unless one uses the `RUSTC_FORCE_INCREMENTAL=1` environment variable added in 1.52.1. [§](https://doc.rust-lang.org/stable/releases.html#internal-only) Internal Only ------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Rework the `std::sys::windows::alloc` implementation.](https://github.com/rust-lang/rust/pull/83065) * [rustdoc: Don’t enter an infer\_ctxt in get\_blanket\_impls for impls that aren’t blanket impls.](https://github.com/rust-lang/rust/pull/82864) * [rustdoc: Only look at blanket impls in `get_blanket_impls`](https://github.com/rust-lang/rust/pull/83681) * [Rework rustdoc const type](https://github.com/rust-lang/rust/pull/82873) [§](https://doc.rust-lang.org/stable/releases.html#version-1521-2021-05-10) Version 1.52.1 (2021-05-10) ======================================================================================================= This release disables incremental compilation, unless the user has explicitly opted in via the newly added RUSTC\_FORCE\_INCREMENTAL=1 environment variable. This is due to the widespread, and frequently occurring, breakage encountered by Rust users due to newly enabled incremental verification in 1.52.0. Notably, Rust users **should** upgrade to 1.52.0 or 1.52.1: the bugs that are detected by newly added incremental verification are still present in past stable versions, and are not yet fixed on any channel. These bugs can lead to miscompilation of Rust binaries. These problems only affect incremental builds, so release builds with Cargo should not be affected unless the user has explicitly opted into incremental. Debug and check builds are affected. See [84970](https://github.com/rust-lang/rust/issues/84970) for more details. [§](https://doc.rust-lang.org/stable/releases.html#version-1520-2021-05-06) Version 1.52.0 (2021-05-06) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-40) Language ------------------------------------------------------------------------ * [Added the `unsafe_op_in_unsafe_fn` lint, which checks whether the unsafe code in an `unsafe fn` is wrapped in a `unsafe` block.](https://github.com/rust-lang/rust/pull/79208) This lint is allowed by default, and may become a warning or hard error in a future edition. * [You can now cast mutable references to arrays to a pointer of the same type as the element.](https://github.com/rust-lang/rust/pull/81479) [§](https://doc.rust-lang.org/stable/releases.html#compiler-40) Compiler ------------------------------------------------------------------------ * [Upgraded the default LLVM to LLVM 12.](https://github.com/rust-lang/rust/pull/81451) Added tier 3\* support for the following targets. * [`s390x-unknown-linux-musl`](https://github.com/rust-lang/rust/pull/82166) * [`riscv32gc-unknown-linux-musl` & `riscv64gc-unknown-linux-musl`](https://github.com/rust-lang/rust/pull/82202) * [`powerpc-unknown-openbsd`](https://github.com/rust-lang/rust/pull/82733) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-40) Libraries -------------------------------------------------------------------------- * [`OsString` now implements `Extend` and `FromIterator`.](https://github.com/rust-lang/rust/pull/82121) * [`cmp::Reverse` now has `#[repr(transparent)]` representation.](https://github.com/rust-lang/rust/pull/81879) * [`Arc` now implements `error::Error`.](https://github.com/rust-lang/rust/pull/80553) * [All integer division and remainder operations are now `const`.](https://github.com/rust-lang/rust/pull/80962) [§](https://doc.rust-lang.org/stable/releases.html#stabilised-apis-4) Stabilised APIs ------------------------------------------------------------------------------------- * [`Arguments::as_str`](https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html#method.as_str) * [`char::MAX`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.MAX) * [`char::REPLACEMENT_CHARACTER`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.REPLACEMENT_CHARACTER) * [`char::UNICODE_VERSION`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.UNICODE_VERSION) * [`char::decode_utf16`](https://doc.rust-lang.org/std/primitive.char.html#method.decode_utf16) * [`char::from_digit`](https://doc.rust-lang.org/std/primitive.char.html#method.from_digit) * [`char::from_u32_unchecked`](https://doc.rust-lang.org/std/primitive.char.html#method.from_u32_unchecked) * [`char::from_u32`](https://doc.rust-lang.org/std/primitive.char.html#method.from_u32) * [`slice::partition_point`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.partition_point) * [`str::rsplit_once`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplit_once) * [`str::split_once`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_once) The following previously stable APIs are now `const`. * [`char::len_utf8`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.len_utf8) * [`char::len_utf16`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.len_utf16) * [`char::to_ascii_uppercase`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_ascii_uppercase) * [`char::to_ascii_lowercase`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.to_ascii_lowercase) * [`char::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.eq_ignore_ascii_case) * [`u8::to_ascii_uppercase`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_ascii_uppercase) * [`u8::to_ascii_lowercase`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_ascii_lowercase) * [`u8::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.eq_ignore_ascii_case) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-22) Rustdoc ---------------------------------------------------------------------- * [Rustdoc lints are now treated as a tool lint, meaning that lints are now prefixed with `rustdoc::` (e.g. `#[warn(rustdoc::broken_intra_doc_links)]`).](https://github.com/rust-lang/rust/pull/80527) Using the old style is still allowed, and will become a warning in a future release. * [Rustdoc now supports argument files.](https://github.com/rust-lang/rust/pull/82261) * [Rustdoc now generates smart punctuation for documentation.](https://github.com/rust-lang/rust/pull/79423) * [You can now use “task lists” in Rustdoc Markdown.](https://github.com/rust-lang/rust/pull/81766) E.g. - [x] Complete - [ ] Todo [§](https://doc.rust-lang.org/stable/releases.html#misc-8) Misc --------------------------------------------------------------- * [You can now pass multiple filters to tests.](https://github.com/rust-lang/rust/pull/81356) E.g. `cargo test -- foo bar` will run all tests that match `foo` and `bar`. * [Rustup now distributes PDB symbols for the `std` library on Windows, allowing you to see `std` symbols when debugging.](https://github.com/rust-lang/rust/pull/82218) [§](https://doc.rust-lang.org/stable/releases.html#internal-only-1) Internal Only --------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Check the result cache before the DepGraph when ensuring queries](https://github.com/rust-lang/rust/pull/81855) * [Try fast\_reject::simplify\_type in coherence before doing full check](https://github.com/rust-lang/rust/pull/81744) * [Only store a LocalDefId in some HIR nodes](https://github.com/rust-lang/rust/pull/81611) * [Store HIR attributes in a side table](https://github.com/rust-lang/rust/pull/79519) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-39) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Cargo build scripts are now forbidden from setting `RUSTC_BOOTSTRAP`.](https://github.com/rust-lang/cargo/pull/9181) * [Removed support for the `x86_64-rumprun-netbsd` target.](https://github.com/rust-lang/rust/pull/82594) * [Deprecated the `x86_64-sun-solaris` target in favor of `x86_64-pc-solaris`.](https://github.com/rust-lang/rust/pull/82216) * [Rustdoc now only accepts `,`, , and `\t` as delimiters for specifying languages in code blocks.](https://github.com/rust-lang/rust/pull/78429) * [Rustc now catches more cases of `pub_use_of_private_extern_crate`](https://github.com/rust-lang/rust/pull/80763) * [Changes in how proc macros handle whitespace may lead to panics when used with older `proc-macro-hack` versions. A `cargo update` should be sufficient to fix this in all cases.](https://github.com/rust-lang/rust/issues/84136) * [Turn `#[derive]` into a regular macro attribute](https://github.com/rust-lang/rust/pull/79078) [§](https://doc.rust-lang.org/stable/releases.html#version-1510-2021-03-25) Version 1.51.0 (2021-03-25) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-41) Language ------------------------------------------------------------------------ * [You can now parameterize items such as functions, traits, and `struct`s by constant values in addition to by types and lifetimes.](https://github.com/rust-lang/rust/pull/79135) Also known as “const generics” E.g. you can now write the following. Note: Only values of primitive integers, `bool`, or `char` types are currently permitted. struct GenericArray { inner: [T; LENGTH] } impl GenericArray { const fn last(&self) -> Option<&T> { if LENGTH == 0 { None } else { Some(&self.inner[LENGTH - 1]) } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+GenericArray%3CT,+const+LENGTH:+usize%3E+%7B%0A++++++++inner:+%5BT;+LENGTH%5D%0A++++%7D%0A++++%0A++++impl%3CT,+const+LENGTH:+usize%3E+GenericArray%3CT,+LENGTH%3E+%7B%0A++++++++const+fn+last(%26self)+-%3E+Option%3C%26T%3E+%7B%0A++++++++++++if+LENGTH+==+0+%7B%0A++++++++++++++++None%0A++++++++++++%7D+else+%7B%0A++++++++++++++++Some(%26self.inner%5BLENGTH+-+1%5D)%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-41) Compiler ------------------------------------------------------------------------ * [Added the `-Csplit-debuginfo` codegen option for macOS platforms.](https://github.com/rust-lang/rust/pull/79570) This option controls whether debug information is split across multiple files or packed into a single file. **Note** This option is unstable on other platforms. * [Added tier 3\* support for `aarch64_be-unknown-linux-gnu`, `aarch64-unknown-linux-gnu_ilp32`, and `aarch64_be-unknown-linux-gnu_ilp32` targets.](https://github.com/rust-lang/rust/pull/81455) * [Added tier 3 support for `i386-unknown-linux-gnu` and `i486-unknown-linux-gnu` targets.](https://github.com/rust-lang/rust/pull/80662) * [The `target-cpu=native` option will now detect individual features of CPUs.](https://github.com/rust-lang/rust/pull/80749) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-41) Libraries -------------------------------------------------------------------------- * [`Box::downcast` is now also implemented for any `dyn Any + Send + Sync` object.](https://github.com/rust-lang/rust/pull/80945) * [`str` now implements `AsMut`.](https://github.com/rust-lang/rust/pull/80279) * [`u64` and `u128` now implement `From`.](https://github.com/rust-lang/rust/pull/79502) * [`Error` is now implemented for `&T` where `T` implements `Error`.](https://github.com/rust-lang/rust/pull/75180) * [`Poll::{map_ok, map_err}` are now implemented for `Poll>>`.](https://github.com/rust-lang/rust/pull/80968) * [`unsigned_abs` is now implemented for all signed integer types.](https://github.com/rust-lang/rust/pull/80959) * [`io::Empty` now implements `io::Seek`.](https://github.com/rust-lang/rust/pull/78044) * [`rc::Weak` and `sync::Weak`’s methods such as `as_ptr` are now implemented for `T: ?Sized` types.](https://github.com/rust-lang/rust/pull/80764) * [`Div` and `Rem` by their `NonZero` variant is now implemented for all unsigned integers.](https://github.com/rust-lang/rust/pull/79134) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-36) Stabilized APIs -------------------------------------------------------------------------------------- * [`Arc::decrement_strong_count`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.decrement_strong_count) * [`Arc::increment_strong_count`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.increment_strong_count) * [`Once::call_once_force`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.call_once_force) * [`Peekable::next_if_eq`](https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html#method.next_if_eq) * [`Peekable::next_if`](https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html#method.next_if) * [`Seek::stream_position`](https://doc.rust-lang.org/nightly/std/io/trait.Seek.html#method.stream_position) * [`array::IntoIter`](https://doc.rust-lang.org/nightly/std/array/struct.IntoIter.html) * [`panic::panic_any`](https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html) * [`ptr::addr_of!`](https://doc.rust-lang.org/nightly/std/ptr/macro.addr_of.html) * [`ptr::addr_of_mut!`](https://doc.rust-lang.org/nightly/std/ptr/macro.addr_of_mut.html) * [`slice::fill_with`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.fill_with) * [`slice::split_inclusive_mut`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_inclusive_mut) * [`slice::split_inclusive`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_inclusive) * [`slice::strip_prefix`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_prefix) * [`slice::strip_suffix`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_suffix) * [`str::split_inclusive`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_inclusive) * [`sync::OnceState`](https://doc.rust-lang.org/stable/std/sync/struct.OnceState.html) * [`task::Wake`](https://doc.rust-lang.org/nightly/std/task/trait.Wake.html) * [`VecDeque::range`](https://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.range) * [`VecDeque::range_mut`](https://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.range_mut) [§](https://doc.rust-lang.org/stable/releases.html#cargo-39) Cargo ------------------------------------------------------------------ * [Added the `split-debuginfo` profile option to control the -Csplit-debuginfo codegen option.](https://github.com/rust-lang/cargo/pull/9112) * [Added the `resolver` field to `Cargo.toml` to enable the new feature resolver and CLI option behavior.](https://github.com/rust-lang/cargo/pull/8997) Version 2 of the feature resolver will try to avoid unifying features of dependencies where that unification could be unwanted. Such as using the same dependency with a `std` feature in a build scripts and proc-macros, while using the `no-std` feature in the final binary. See the [Cargo book documentation](https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2) for more information on the feature. [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-23) Rustdoc ---------------------------------------------------------------------- * [Rustdoc will now include documentation for methods available from _nested_ `Deref` traits.](https://github.com/rust-lang/rust/pull/80653) * [You can now provide a `--default-theme` flag which sets the default theme to use for documentation.](https://github.com/rust-lang/rust/pull/79642) Various improvements to intra-doc links: * [You can link to non-path primitives such as `slice`.](https://github.com/rust-lang/rust/pull/80181) * [You can link to associated items.](https://github.com/rust-lang/rust/pull/74489) * [You can now include generic parameters when linking to items, like `Vec`.](https://github.com/rust-lang/rust/pull/76934) [§](https://doc.rust-lang.org/stable/releases.html#misc-9) Misc --------------------------------------------------------------- * [You can now pass `--include-ignored` to tests (e.g. with `cargo test -- --include-ignored`) to include testing tests marked `#[ignore]`.](https://github.com/rust-lang/rust/pull/80053) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-40) Compatibility Notes ---------------------------------------------------------------------------------------------- * [WASI platforms no longer use the `wasm-bindgen` ABI, and instead use the wasm32 ABI.](https://github.com/rust-lang/rust/pull/79998) * [`rustc` no longer promotes division, modulo and indexing operations to `const` that could fail.](https://github.com/rust-lang/rust/pull/80579) * [The minimum version of glibc for the following platforms has been bumped to version 2.31 for the distributed artifacts.](https://github.com/rust-lang/rust/pull/81521) * `armv5te-unknown-linux-gnueabi` * `sparc64-unknown-linux-gnu` * `thumbv7neon-unknown-linux-gnueabihf` * `armv7-unknown-linux-gnueabi` * `x86_64-unknown-linux-gnux32` * [`atomic::spin_loop_hint` has been deprecated.](https://github.com/rust-lang/rust/pull/80966) It’s recommended to use `hint::spin_loop` instead. [§](https://doc.rust-lang.org/stable/releases.html#internal-only-2) Internal Only --------------------------------------------------------------------------------- * [Consistently avoid constructing optimized MIR when not doing codegen](https://github.com/rust-lang/rust/pull/80718) [§](https://doc.rust-lang.org/stable/releases.html#version-1500-2021-02-11) Version 1.50.0 (2021-02-11) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-42) Language ------------------------------------------------------------------------ * [You can now use `const` values for `x` in `[x; N]` array expressions.](https://github.com/rust-lang/rust/pull/79270) This has been technically possible since 1.38.0, as it was unintentionally stabilized. * [Assignments to `ManuallyDrop` union fields are now considered safe.](https://github.com/rust-lang/rust/pull/78068) [§](https://doc.rust-lang.org/stable/releases.html#compiler-42) Compiler ------------------------------------------------------------------------ * [Added tier 3\* support for the `armv5te-unknown-linux-uclibceabi` target.](https://github.com/rust-lang/rust/pull/78142) * [Added tier 3 support for the `aarch64-apple-ios-macabi` target.](https://github.com/rust-lang/rust/pull/77484) * [The `x86_64-unknown-freebsd` is now built with the full toolset.](https://github.com/rust-lang/rust/pull/79484) * [Dropped support for all cloudabi targets.](https://github.com/rust-lang/rust/pull/78439) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-42) Libraries -------------------------------------------------------------------------- * [`proc_macro::Punct` now implements `PartialEq`.](https://github.com/rust-lang/rust/pull/78636) * [`ops::{Index, IndexMut}` are now implemented for fixed sized arrays of any length.](https://github.com/rust-lang/rust/pull/74989) * [On Unix platforms, the `std::fs::File` type now has a “niche” of `-1`.](https://github.com/rust-lang/rust/pull/74699) This value cannot be a valid file descriptor, and now means `Option` takes up the same amount of space as `File`. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-37) Stabilized APIs -------------------------------------------------------------------------------------- * [`bool::then`](https://doc.rust-lang.org/stable/std/primitive.bool.html#method.then) * [`btree_map::Entry::or_insert_with_key`](https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry.html#method.or_insert_with_key) * [`f32::clamp`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.clamp) * [`f64::clamp`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.clamp) * [`hash_map::Entry::or_insert_with_key`](https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.or_insert_with_key) * [`Ord::clamp`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) * [`RefCell::take`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.take) * [`slice::fill`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.fill) * [`UnsafeCell::get_mut`](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html#method.get_mut) The following previously stable methods are now `const`. * [`IpAddr::is_ipv4`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv4) * [`IpAddr::is_ipv6`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv6) * [`IpAddr::is_unspecified`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_unspecified) * [`IpAddr::is_loopback`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_loopback) * [`IpAddr::is_multicast`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_multicast) * [`Ipv4Addr::octets`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.octets) * [`Ipv4Addr::is_loopback`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_loopback) * [`Ipv4Addr::is_private`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_private) * [`Ipv4Addr::is_link_local`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_link_local) * [`Ipv4Addr::is_multicast`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_multicast) * [`Ipv4Addr::is_broadcast`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_broadcast) * [`Ipv4Addr::is_documentation`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_documentation) * [`Ipv4Addr::to_ipv6_compatible`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.to_ipv6_compatible) * [`Ipv4Addr::to_ipv6_mapped`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.to_ipv6_mapped) * [`Ipv6Addr::segments`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.segments) * [`Ipv6Addr::is_unspecified`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_unspecified) * [`Ipv6Addr::is_loopback`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_loopback) * [`Ipv6Addr::is_multicast`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_multicast) * [`Ipv6Addr::to_ipv4`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.to_ipv4) * [`Layout::size`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.size) * [`Layout::align`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.align) * [`Layout::from_size_align`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.from_size_align) * `pow` for all integer types. * `checked_pow` for all integer types. * `saturating_pow` for all integer types. * `wrapping_pow` for all integer types. * `next_power_of_two` for all unsigned integer types. * `checked_next_power_of_two` for all unsigned integer types. [§](https://doc.rust-lang.org/stable/releases.html#cargo-40) Cargo ------------------------------------------------------------------ * [Added the `[build.rustc-workspace-wrapper]` option.](https://github.com/rust-lang/cargo/pull/8976) This option sets a wrapper to execute instead of `rustc`, for workspace members only. * [`cargo:rerun-if-changed` will now, if provided a directory, scan the entire contents of that directory for changes.](https://github.com/rust-lang/cargo/pull/8973) * [Added the `--workspace` flag to the `cargo update` command.](https://github.com/rust-lang/cargo/pull/8725) [§](https://doc.rust-lang.org/stable/releases.html#misc-10) Misc ---------------------------------------------------------------- * [The search results tab and the help button are focusable with keyboard in rustdoc.](https://github.com/rust-lang/rust/pull/79896) * [Running tests will now print the total time taken to execute.](https://github.com/rust-lang/rust/pull/75752) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-41) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The `compare_and_swap` method on atomics has been deprecated.](https://github.com/rust-lang/rust/pull/79261) It’s recommended to use the `compare_exchange` and `compare_exchange_weak` methods instead. * [Changes in how `TokenStream`s are checked have fixed some cases where you could write unhygenic `macro_rules!` macros.](https://github.com/rust-lang/rust/pull/79472) * [`#![test]` as an inner attribute is now considered unstable like other inner macro attributes, and reports an error by default through the `soft_unstable` lint.](https://github.com/rust-lang/rust/pull/79003) * [Overriding a `forbid` lint at the same level that it was set is now a hard error.](https://github.com/rust-lang/rust/pull/78864) * [You can no longer intercept `panic!` calls by supplying your own macro.](https://github.com/rust-lang/rust/pull/78343) It’s recommended to use the `#[panic_handler]` attribute to provide your own implementation. * [Semi-colons after item statements (e.g. `struct Foo {};`) now produce a warning.](https://github.com/rust-lang/rust/pull/78296) [§](https://doc.rust-lang.org/stable/releases.html#version-1490-2020-12-31) Version 1.49.0 (2020-12-31) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-43) Language ------------------------------------------------------------------------ * [Unions can now implement `Drop`, and you can now have a field in a union with `ManuallyDrop`.](https://github.com/rust-lang/rust/pull/77547) * [You can now cast uninhabited enums to integers.](https://github.com/rust-lang/rust/pull/76199) * [You can now bind by reference and by move in patterns.](https://github.com/rust-lang/rust/pull/76119) This allows you to selectively borrow individual components of a type. E.g. #[derive(Debug)] struct Person { name: String, age: u8, } let person = Person { name: String::from("Alice"), age: 20, }; // `name` is moved out of person, but `age` is referenced. let Person { name, ref age } = person; println!("{} {}", name, age); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(Debug)%5D%0A++++struct+Person+%7B%0A++++++++name:+String,%0A++++++++age:+u8,%0A++++%7D%0A++++%0A++++let+person+=+Person+%7B%0A++++++++name:+String::from(%22Alice%22),%0A++++++++age:+20,%0A++++%7D;%0A++++%0A++++//+%60name%60+is+moved+out+of+person,+but+%60age%60+is+referenced.%0A++++let+Person+%7B+name,+ref+age+%7D+=+person;%0A++++println!(%22%7B%7D+%7B%7D%22,+name,+age);%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-43) Compiler ------------------------------------------------------------------------ * [Added tier 1\* support for `aarch64-unknown-linux-gnu`.](https://github.com/rust-lang/rust/pull/78228) * [Added tier 2 support for `aarch64-apple-darwin`.](https://github.com/rust-lang/rust/pull/75991) * [Added tier 2 support for `aarch64-pc-windows-msvc`.](https://github.com/rust-lang/rust/pull/75914) * [Added tier 3 support for `mipsel-unknown-none`.](https://github.com/rust-lang/rust/pull/78676) * [Raised the minimum supported LLVM version to LLVM 9.](https://github.com/rust-lang/rust/pull/78848) * [Output from threads spawned in tests is now captured.](https://github.com/rust-lang/rust/pull/78227) * [Change os and vendor values to “none” and “unknown” for some targets](https://github.com/rust-lang/rust/pull/78951) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-43) Libraries -------------------------------------------------------------------------- * [`RangeInclusive` now checks for exhaustion when calling `contains` and indexing.](https://github.com/rust-lang/rust/pull/78109) * [`ToString::to_string` now no longer shrinks the internal buffer in the default implementation.](https://github.com/rust-lang/rust/pull/77997) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-38) Stabilized APIs -------------------------------------------------------------------------------------- * [`slice::select_nth_unstable`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.select_nth_unstable) * [`slice::select_nth_unstable_by`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.select_nth_unstable_by) * [`slice::select_nth_unstable_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.select_nth_unstable_by_key) The following previously stable methods are now `const`. * [`Poll::is_ready`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html#method.is_ready) * [`Poll::is_pending`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html#method.is_pending) [§](https://doc.rust-lang.org/stable/releases.html#cargo-41) Cargo ------------------------------------------------------------------ * [Building a crate with `cargo-package` should now be independently reproducible.](https://github.com/rust-lang/cargo/pull/8864) * [`cargo-tree` now marks proc-macro crates.](https://github.com/rust-lang/cargo/pull/8765) * [Added `CARGO_PRIMARY_PACKAGE` build-time environment variable.](https://github.com/rust-lang/cargo/pull/8758) This variable will be set if the crate being built is one the user selected to build, either with `-p` or through defaults. * [You can now use glob patterns when specifying packages & targets.](https://github.com/rust-lang/cargo/pull/8752) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-42) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Demoted `i686-unknown-freebsd` from host tier 2 to target tier 2 support.](https://github.com/rust-lang/rust/pull/78746) * [Macros that end with a semi-colon are now treated as statements even if they expand to nothing.](https://github.com/rust-lang/rust/pull/78376) * [Rustc will now check for the validity of some built-in attributes on enum variants.](https://github.com/rust-lang/rust/pull/77015) Previously such invalid or unused attributes could be ignored. * Leading whitespace is stripped more uniformly in documentation comments, which may change behavior. You read [this post about the changes](https://blog.guillaume-gomez.fr/articles/2020-11-11+New+doc+comment+handling+in+rustdoc) for more details. * [Trait bounds are no longer inferred for associated types.](https://github.com/rust-lang/rust/issues/79904) [§](https://doc.rust-lang.org/stable/releases.html#internal-only-3) Internal Only --------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [rustc’s internal crates are now compiled using the `initial-exec` Thread Local Storage model.](https://github.com/rust-lang/rust/pull/78201) * [Calculate visibilities once in resolve.](https://github.com/rust-lang/rust/pull/78077) * [Added `system` to the `llvm-libunwind` bootstrap config option.](https://github.com/rust-lang/rust/pull/77703) * [Added `--color` for configuring terminal color support to bootstrap.](https://github.com/rust-lang/rust/pull/79004) [§](https://doc.rust-lang.org/stable/releases.html#version-1480-2020-11-19) Version 1.48.0 (2020-11-19) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-44) Language ------------------------------------------------------------------------ * [The `unsafe` keyword is now syntactically permitted on modules.](https://github.com/rust-lang/rust/pull/75857/) This is still rejected _semantically_, but can now be parsed by procedural macros. [§](https://doc.rust-lang.org/stable/releases.html#compiler-44) Compiler ------------------------------------------------------------------------ * [Stabilised the `-C link-self-contained=` compiler flag.](https://github.com/rust-lang/rust/pull/76158/) This tells `rustc` whether to link its own C runtime and libraries or to rely on a external linker to find them. (Supported only on `windows-gnu`, `linux-musl`, and `wasi` platforms.) * [You can now use `-C target-feature=+crt-static` on `linux-gnu` targets.](https://github.com/rust-lang/rust/pull/77386/) Note: If you’re using cargo you must explicitly pass the `--target` flag. * [Added tier 2\* support for `aarch64-unknown-linux-musl`.](https://github.com/rust-lang/rust/pull/76420/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-44) Libraries -------------------------------------------------------------------------- * [`io::Write` is now implemented for `&ChildStdin` `&Sink`, `&Stdout`, and `&Stderr`.](https://github.com/rust-lang/rust/pull/76275/) * [All arrays of any length now implement `TryFrom>`.](https://github.com/rust-lang/rust/pull/76310/) * [The `matches!` macro now supports having a trailing comma.](https://github.com/rust-lang/rust/pull/74880/) * [`Vec` now implements `PartialEq<[B]>` where `A: PartialEq`.](https://github.com/rust-lang/rust/pull/74194/) * [The `RefCell::{replace, replace_with, clone}` methods now all use `#[track_caller]`.](https://github.com/rust-lang/rust/pull/77055/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-39) Stabilized APIs -------------------------------------------------------------------------------------- * [`slice::as_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr_range) * [`slice::as_mut_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr_range) * [`VecDeque::make_contiguous`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.make_contiguous) * [`future::pending`](https://doc.rust-lang.org/std/future/fn.pending.html) * [`future::ready`](https://doc.rust-lang.org/std/future/fn.ready.html) The following previously stable methods are now `const fn`’s: * [`Option::is_some`](https://doc.rust-lang.org/std/option/enum.Option.html#method.is_some) * [`Option::is_none`](https://doc.rust-lang.org/std/option/enum.Option.html#method.is_none) * [`Option::as_ref`](https://doc.rust-lang.org/std/option/enum.Option.html#method.as_ref) * [`Result::is_ok`](https://doc.rust-lang.org/std/result/enum.Result.html#method.is_ok) * [`Result::is_err`](https://doc.rust-lang.org/std/result/enum.Result.html#method.is_err) * [`Result::as_ref`](https://doc.rust-lang.org/std/result/enum.Result.html#method.as_ref) * [`Ordering::reverse`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.reverse) * [`Ordering::then`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.then) [§](https://doc.rust-lang.org/stable/releases.html#cargo-42) Cargo ------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-24) Rustdoc ---------------------------------------------------------------------- * [You can now link to items in `rustdoc` using the intra-doc link syntax.](https://github.com/rust-lang/rust/pull/74430/) E.g. ``/// Uses [`std::future`]`` will automatically generate a link to `std::future`’s documentation. See [“Linking to items by name”](https://doc.rust-lang.org/rustdoc/linking-to-items-by-name.html) for more information. * [You can now specify `#[doc(alias = "")]` on items to add search aliases when searching through `rustdoc`’s UI.](https://github.com/rust-lang/rust/pull/75740/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-43) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Promotion of references to `'static` lifetime inside `const fn` now follows the same rules as inside a `fn` body.](https://github.com/rust-lang/rust/pull/75502/) In particular, `&foo()` will not be promoted to `'static` lifetime any more inside `const fn`s. * [Associated type bindings on trait objects are now verified to meet the bounds declared on the trait when checking that they implement the trait.](https://github.com/rust-lang/rust/issues/27675/) * [When trait bounds on associated types or opaque types are ambiguous, the compiler no longer makes an arbitrary choice on which bound to use.](https://github.com/rust-lang/rust/issues/54121/) * [Fixed recursive nonterminals not being expanded in macros during pretty-print/reparse check.](https://github.com/rust-lang/rust/pull/77153/) This may cause errors if your macro wasn’t correctly handling recursive nonterminal tokens. * [`&mut` references to non zero-sized types are no longer promoted.](https://github.com/rust-lang/rust/pull/75585/) * [`rustc` will now warn if you use attributes like `#[link_name]` or `#[cold]` in places where they have no effect.](https://github.com/rust-lang/rust/pull/73461/) * [Updated `_mm256_extract_epi8` and `_mm256_extract_epi16` signatures in `arch::{x86, x86_64}` to return `i32` to match the vendor signatures.](https://github.com/rust-lang/rust/pull/73166/) * [`mem::uninitialized` will now panic if any inner types inside a struct or enum disallow zero-initialization.](https://github.com/rust-lang/rust/pull/71274/) * [`#[target_feature]` will now error if used in a place where it has no effect.](https://github.com/rust-lang/rust/issues/78143) * [Foreign exceptions are now caught by `catch_unwind` and will cause an abort.](https://github.com/rust-lang/rust/pull/70212/) Note: This behaviour is not guaranteed and is still considered undefined behaviour, see the [`catch_unwind`](https://doc.rust-lang.org/std/panic/fn.catch_unwind.html) documentation for further information. [§](https://doc.rust-lang.org/stable/releases.html#internal-only-4) Internal Only --------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [Building `rustc` from source now uses `ninja` by default over `make`.](https://github.com/rust-lang/rust/pull/74922/) You can continue building with `make` by setting `ninja=false` in your `bootstrap.toml`. * [cg\_llvm: `fewer_names` in `uncached_llvm_type`](https://github.com/rust-lang/rust/pull/76030/) * [Made `ensure_sufficient_stack()` non-generic](https://github.com/rust-lang/rust/pull/76680/) [§](https://doc.rust-lang.org/stable/releases.html#version-1470-2020-10-08) Version 1.47.0 (2020-10-08) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-45) Language ------------------------------------------------------------------------ * [Closures will now warn when not used.](https://github.com/rust-lang/rust/pull/74869/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-45) Compiler ------------------------------------------------------------------------ * [Stabilized the `-C control-flow-guard` codegen option](https://github.com/rust-lang/rust/pull/73893/) , which enables [Control Flow Guard](https://docs.microsoft.com/en-us/windows/win32/secbp/control-flow-guard) for Windows platforms, and is ignored on other platforms. * [Upgraded to LLVM 11.](https://github.com/rust-lang/rust/pull/73526/) * [Added tier 3\* support for the `thumbv4t-none-eabi` target.](https://github.com/rust-lang/rust/pull/74419/) * [Upgrade the FreeBSD toolchain to version 11.4](https://github.com/rust-lang/rust/pull/75204/) * [`RUST_BACKTRACE`’s output is now more compact.](https://github.com/rust-lang/rust/pull/75048/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-45) Libraries -------------------------------------------------------------------------- * [`CStr` now implements `Index>`.](https://github.com/rust-lang/rust/pull/74021/) * [Traits in `std`/`core` are now implemented for arrays of any length, not just those of length less than 33.](https://github.com/rust-lang/rust/pull/74060/) * [`ops::RangeFull` and `ops::Range` now implement Default.](https://github.com/rust-lang/rust/pull/73197/) * [`panic::Location` now implements `Copy`, `Clone`, `Eq`, `Hash`, `Ord`, `PartialEq`, and `PartialOrd`.](https://github.com/rust-lang/rust/pull/73583/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-40) Stabilized APIs -------------------------------------------------------------------------------------- * [`Ident::new_raw`](https://doc.rust-lang.org/nightly/proc_macro/struct.Ident.html#method.new_raw) * [`Range::is_empty`](https://doc.rust-lang.org/nightly/std/ops/struct.Range.html#method.is_empty) * [`RangeInclusive::is_empty`](https://doc.rust-lang.org/nightly/std/ops/struct.RangeInclusive.html#method.is_empty) * [`Result::as_deref`](https://doc.rust-lang.org/nightly/std/result/enum.Result.html#method.as_deref) * [`Result::as_deref_mut`](https://doc.rust-lang.org/nightly/std/result/enum.Result.html#method.as_deref_mut) * [`Vec::leak`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.leak) * [`pointer::offset_from`](https://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.offset_from) * [`f32::TAU`](https://doc.rust-lang.org/nightly/std/f32/consts/constant.TAU.html) * [`f64::TAU`](https://doc.rust-lang.org/nightly/std/f64/consts/constant.TAU.html) The following previously stable APIs have now been made const. * [The `new` method for all `NonZero` integers.](https://github.com/rust-lang/rust/pull/73858/) * [The `checked_add`,`checked_sub`,`checked_mul`,`checked_neg`, `checked_shl`, `checked_shr`, `saturating_add`, `saturating_sub`, and `saturating_mul` methods for all integers.](https://github.com/rust-lang/rust/pull/73858/) * [The `checked_abs`, `saturating_abs`, `saturating_neg`, and `signum` for all signed integers.](https://github.com/rust-lang/rust/pull/73858/) * [The `is_ascii_alphabetic`, `is_ascii_uppercase`, `is_ascii_lowercase`, `is_ascii_alphanumeric`, `is_ascii_digit`, `is_ascii_hexdigit`, `is_ascii_punctuation`, `is_ascii_graphic`, `is_ascii_whitespace`, and `is_ascii_control` methods for `char` and `u8`.](https://github.com/rust-lang/rust/pull/73858/) [§](https://doc.rust-lang.org/stable/releases.html#cargo-43) Cargo ------------------------------------------------------------------ * [`build-dependencies` are now built with opt-level 0 by default.](https://github.com/rust-lang/cargo/pull/8500/) You can override this by setting the following in your `Cargo.toml`. [profile.release.build-override] opt-level = 3 * [`cargo-help` will now display man pages for commands rather just the `--help` text.](https://github.com/rust-lang/cargo/pull/8456/) * [`cargo-metadata` now emits a `test` field indicating if a target has tests enabled.](https://github.com/rust-lang/cargo/pull/8478/) * [`workspace.default-members` now respects `workspace.exclude`.](https://github.com/rust-lang/cargo/pull/8485/) * [`cargo-publish` will now use an alternative registry by default if it’s the only registry specified in `package.publish`.](https://github.com/rust-lang/cargo/pull/8571/) [§](https://doc.rust-lang.org/stable/releases.html#misc-11) Misc ---------------------------------------------------------------- * [Added a help button beside Rustdoc’s searchbar that explains rustdoc’s type based search.](https://github.com/rust-lang/rust/pull/75366/) * [Added the Ayu theme to rustdoc.](https://github.com/rust-lang/rust/pull/71237/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-44) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Bumped the minimum supported Emscripten version to 1.39.20.](https://github.com/rust-lang/rust/pull/75716/) * [Fixed a regression parsing `{} && false` in tail expressions.](https://github.com/rust-lang/rust/pull/74650/) * [Added changes to how proc-macros are expanded in `macro_rules!` that should help to preserve more span information.](https://github.com/rust-lang/rust/pull/73084/) These changes may cause compilation errors if your macro was unhygenic or didn’t correctly handle `Delimiter::None`. * [Moved support for the CloudABI target to tier 3.](https://github.com/rust-lang/rust/pull/75568/) * [`linux-gnu` targets now require minimum kernel 2.6.32 and glibc 2.11.](https://github.com/rust-lang/rust/pull/74163/) * [Added the `rustc-docs` component.](https://github.com/rust-lang/rust/pull/75560/) This allows you to install and read the documentation for the compiler internal APIs. (Currently only available for `x86_64-unknown-linux-gnu`.) [§](https://doc.rust-lang.org/stable/releases.html#internal-only-5) Internal Only --------------------------------------------------------------------------------- * [Improved default settings for bootstrapping in `x.py`.](https://github.com/rust-lang/rust/pull/73964/) You can read details about this change in the [“Changes to `x.py` defaults”](https://blog.rust-lang.org/inside-rust/2020/08/30/changes-to-x-py-defaults.html) post on the Inside Rust blog. [§](https://doc.rust-lang.org/stable/releases.html#version-1460-2020-08-27) Version 1.46.0 (2020-08-27) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-46) Language ------------------------------------------------------------------------ * [`if`, `match`, and `loop` expressions can now be used in const functions.](https://github.com/rust-lang/rust/pull/72437/) * [Additionally you are now also able to coerce and cast to slices (`&[T]`) in const functions.](https://github.com/rust-lang/rust/pull/73862/) * [The `#[track_caller]` attribute can now be added to functions to use the function’s caller’s location information for panic messages.](https://github.com/rust-lang/rust/pull/72445/) * [Recursively indexing into tuples no longer needs parentheses.](https://github.com/rust-lang/rust/pull/71322/) E.g. `x.0.0` over `(x.0).0`. * [`mem::transmute` can now be used in statics and constants.](https://github.com/rust-lang/rust/pull/72920/) **Note** You currently can’t use `mem::transmute` in constant functions. [§](https://doc.rust-lang.org/stable/releases.html#compiler-46) Compiler ------------------------------------------------------------------------ * [You can now use the `cdylib` target on Apple iOS and tvOS platforms.](https://github.com/rust-lang/rust/pull/73516/) * [Enabled static “Position Independent Executables” by default for `x86_64-unknown-linux-musl`.](https://github.com/rust-lang/rust/pull/70740/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-46) Libraries -------------------------------------------------------------------------- * [`mem::forget` is now a `const fn`.](https://github.com/rust-lang/rust/pull/73887/) * [`String` now implements `From`.](https://github.com/rust-lang/rust/pull/73466/) * [The `leading_ones`, and `trailing_ones` methods have been stabilised for all integer types.](https://github.com/rust-lang/rust/pull/73032/) * [`vec::IntoIter` now implements `AsRef<[T]>`.](https://github.com/rust-lang/rust/pull/72583/) * [All non-zero integer types (`NonZeroU8`) now implement `TryFrom` for their zero-able equivalent (e.g. `TryFrom`).](https://github.com/rust-lang/rust/pull/72717/) * [`&[T]` and `&mut [T]` now implement `PartialEq>`.](https://github.com/rust-lang/rust/pull/71660/) * [`(String, u16)` now implements `ToSocketAddrs`.](https://github.com/rust-lang/rust/pull/73007/) * [`vec::Drain<'_, T>` now implements `AsRef<[T]>`.](https://github.com/rust-lang/rust/pull/72584/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-41) Stabilized APIs -------------------------------------------------------------------------------------- * [`Option::zip`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.zip) * [`vec::Drain::as_slice`](https://doc.rust-lang.org/stable/std/vec/struct.Drain.html#method.as_slice) [§](https://doc.rust-lang.org/stable/releases.html#cargo-44) Cargo ------------------------------------------------------------------ Added a number of new environment variables that are now available when compiling your crate. * [`CARGO_BIN_NAME` and `CARGO_CRATE_NAME`](https://github.com/rust-lang/cargo/pull/8270/) Providing the name of the specific binary being compiled and the name of the crate. * [`CARGO_PKG_LICENSE`](https://github.com/rust-lang/cargo/pull/8325/) The license from the manifest of the package. * [`CARGO_PKG_LICENSE_FILE`](https://github.com/rust-lang/cargo/pull/8387/) The path to the license file. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-45) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The target configuration option `abi_blacklist` has been renamed to `unsupported_abis`.](https://github.com/rust-lang/rust/pull/74150/) The old name will still continue to work. * [Rustc will now warn if you cast a C-like enum that implements `Drop`.](https://github.com/rust-lang/rust/pull/72331/) This was previously accepted but will become a hard error in a future release. * [Rustc will fail to compile if you have a struct with `#[repr(i128)]` or `#[repr(u128)]`.](https://github.com/rust-lang/rust/pull/74109/) This representation is currently only allowed on `enum`s. * [Tokens passed to `macro_rules!` are now always captured.](https://github.com/rust-lang/rust/pull/73293/) This helps ensure that spans have the correct information, and may cause breakage if you were relying on receiving spans with dummy information. * [The InnoSetup installer for Windows is no longer available.](https://github.com/rust-lang/rust/pull/72569/) This was a legacy installer that was replaced by a MSI installer a few years ago but was still being built. * [`{f32, f64}::asinh` now returns the correct values for negative numbers.](https://github.com/rust-lang/rust/pull/72486/) * [Rustc will no longer accept overlapping trait implementations that only differ in how the lifetime was bound.](https://github.com/rust-lang/rust/pull/72493/) * [Rustc now correctly relates the lifetime of an existential associated type.](https://github.com/rust-lang/rust/pull/71896/) This fixes some edge cases where `rustc` would erroneously allow you to pass a shorter lifetime than expected. * [Rustc now dynamically links to `libz` (also called `zlib`) on Linux.](https://github.com/rust-lang/rust/issues/74420/) The library will need to be installed for `rustc` to work, even though we expect it to be already available on most systems. * [Tests annotated with `#[should_panic]` are broken on ARMv7 while running under QEMU.](https://github.com/rust-lang/rust/issues/74820/) * [Pretty printing of some tokens in procedural macros changed.](https://github.com/rust-lang/rust/issues/75453/) The exact output returned by rustc’s pretty printing is an unstable implementation detail: we recommend any macro relying on it to switch to a more robust parsing system. [§](https://doc.rust-lang.org/stable/releases.html#version-1452-2020-08-03) Version 1.45.2 (2020-08-03) ======================================================================================================= * [Fix bindings in tuple struct patterns](https://github.com/rust-lang/rust/issues/74954) * [Fix track\_caller integration with trait objects](https://github.com/rust-lang/rust/issues/74784) [§](https://doc.rust-lang.org/stable/releases.html#version-1451-2020-07-30) Version 1.45.1 (2020-07-30) ======================================================================================================= * [Fix const propagation with references.](https://github.com/rust-lang/rust/pull/73613) * [rustfmt accepts rustfmt\_skip in cfg\_attr again.](https://github.com/rust-lang/rust/issues/73078) * [Avoid spurious implicit region bound.](https://github.com/rust-lang/rust/pull/74509) * [Install clippy on x.py install](https://github.com/rust-lang/rust/pull/74457) [§](https://doc.rust-lang.org/stable/releases.html#version-1450-2020-07-16) Version 1.45.0 (2020-07-16) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-47) Language ------------------------------------------------------------------------ * [Out of range float to int conversions using `as` has been defined as a saturating conversion.](https://github.com/rust-lang/rust/pull/71269/) This was previously undefined behaviour, but you can use the `{f64, f32}::to_int_unchecked` methods to continue using the current behaviour, which may be desirable in rare performance sensitive situations. * [`mem::Discriminant` now uses `T`’s discriminant type instead of always using `u64`.](https://github.com/rust-lang/rust/pull/70705/) * [Function like procedural macros can now be used in expression, pattern, and statement positions.](https://github.com/rust-lang/rust/pull/68717/) This means you can now use a function-like procedural macro anywhere you can use a declarative (`macro_rules!`) macro. [§](https://doc.rust-lang.org/stable/releases.html#compiler-47) Compiler ------------------------------------------------------------------------ * [You can now override individual target features through the `target-feature` flag.](https://github.com/rust-lang/rust/pull/72094/) E.g. `-C target-feature=+avx2 -C target-feature=+fma` is now equivalent to `-C target-feature=+avx2,+fma`. * [Added the `force-unwind-tables` flag.](https://github.com/rust-lang/rust/pull/69984/) This option allows rustc to always generate unwind tables regardless of panic strategy. * [Added the `embed-bitcode` flag.](https://github.com/rust-lang/rust/pull/71716/) This codegen flag allows rustc to include LLVM bitcode into generated `rlib`s (this is on by default). * [Added the `tiny` value to the `code-model` codegen flag.](https://github.com/rust-lang/rust/pull/72397/) * [Added tier 3 support\* for the `mipsel-sony-psp` target.](https://github.com/rust-lang/rust/pull/72062/) * [Added tier 3 support for the `thumbv7a-uwp-windows-msvc` target.](https://github.com/rust-lang/rust/pull/72133/) * [Upgraded to LLVM 10.](https://github.com/rust-lang/rust/pull/67759/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-47) Libraries -------------------------------------------------------------------------- * [`net::{SocketAddr, SocketAddrV4, SocketAddrV6}` now implements `PartialOrd` and `Ord`.](https://github.com/rust-lang/rust/pull/72239/) * [`proc_macro::TokenStream` now implements `Default`.](https://github.com/rust-lang/rust/pull/72234/) * [You can now use `char` with `ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo}` to iterate over a range of codepoints.](https://github.com/rust-lang/rust/pull/72413/) E.g. you can now write the following; for ch in 'a'..='z' { print!("{}", ch); } println!(); // Prints "abcdefghijklmnopqrstuvwxyz" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++for+ch+in+%27a%27..=%27z%27+%7B%0A++++++++print!(%22%7B%7D%22,+ch);%0A++++%7D%0A++++println!();%0A%7D&edition=2015 "Run code") * [`OsString` now implements `FromStr`.](https://github.com/rust-lang/rust/pull/71662/) * [The `saturating_neg` method has been added to all signed integer primitive types, and the `saturating_abs` method has been added for all integer primitive types.](https://github.com/rust-lang/rust/pull/71886/) * [`Arc`, `Rc` now implement `From>`, and `Box` now implements `From` when `T` is `[T: Copy]`, `str`, `CStr`, `OsStr`, or `Path`.](https://github.com/rust-lang/rust/pull/71447/) * [`Box<[T]>` now implements `From<[T; N]>`.](https://github.com/rust-lang/rust/pull/71095/) * [`BitOr` and `BitOrAssign` are implemented for all `NonZero` integer types.](https://github.com/rust-lang/rust/pull/69813/) * [The `fetch_min`, and `fetch_max` methods have been added to all atomic integer types.](https://github.com/rust-lang/rust/pull/72324/) * [The `fetch_update` method has been added to all atomic integer types.](https://github.com/rust-lang/rust/pull/71843/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-42) Stabilized APIs -------------------------------------------------------------------------------------- * [`Arc::as_ptr`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.as_ptr) * [`BTreeMap::remove_entry`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html#method.remove_entry) * [`Rc::as_ptr`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.as_ptr) * [`rc::Weak::as_ptr`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.as_ptr) * [`rc::Weak::from_raw`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.from_raw) * [`rc::Weak::into_raw`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.into_raw) * [`str::strip_prefix`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.strip_prefix) * [`str::strip_suffix`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.strip_suffix) * [`sync::Weak::as_ptr`](https://doc.rust-lang.org/stable/std/sync/struct.Weak.html#method.as_ptr) * [`sync::Weak::from_raw`](https://doc.rust-lang.org/stable/std/sync/struct.Weak.html#method.from_raw) * [`sync::Weak::into_raw`](https://doc.rust-lang.org/stable/std/sync/struct.Weak.html#method.into_raw) * [`char::UNICODE_VERSION`](https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.UNICODE_VERSION) * [`Span::resolved_at`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.resolved_at) * [`Span::located_at`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.located_at) * [`Span::mixed_site`](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html#method.mixed_site) * [`unix::process::CommandExt::arg0`](https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.arg0) [§](https://doc.rust-lang.org/stable/releases.html#cargo-45) Cargo ------------------------------------------------------------------ * [Cargo uses the `embed-bitcode` flag to optimize disk usage and build time.](https://github.com/rust-lang/cargo/pull/8066) [§](https://doc.rust-lang.org/stable/releases.html#misc-12) Misc ---------------------------------------------------------------- * [Rustdoc now supports strikethrough text in Markdown.](https://github.com/rust-lang/rust/pull/71928/) E.g. `~~outdated information~~` becomes “~outdated information~”. * [Added an emoji to Rustdoc’s deprecated API message.](https://github.com/rust-lang/rust/pull/72014/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-46) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Trying to self initialize a static value (that is creating a value using itself) is unsound and now causes a compile error.](https://github.com/rust-lang/rust/pull/71140/) * [`{f32, f64}::powi` now returns a slightly different value on Windows.](https://github.com/rust-lang/rust/issues/73420/) This is due to changes in LLVM’s intrinsics which `{f32, f64}::powi` uses. * [Rustdoc’s CLI’s extra error exit codes have been removed.](https://github.com/rust-lang/rust/pull/71900/) These were previously undocumented and not intended for public use. Rustdoc still provides a non-zero exit code on errors. * [Rustc’s `lto` flag is incompatible with the new `embed-bitcode=no`.](https://github.com/rust-lang/rust/issues/71848/) This may cause issues if LTO is enabled through `RUSTFLAGS` or `cargo rustc` flags while cargo is adding `embed-bitcode` itself. The recommended way to control LTO is with Cargo profiles, either in `Cargo.toml` or `.cargo/config`, or by setting `CARGO_PROFILE__LTO` in the environment. [§](https://doc.rust-lang.org/stable/releases.html#internals-only) Internals Only --------------------------------------------------------------------------------- * [Make clippy a git subtree instead of a git submodule](https://github.com/rust-lang/rust/pull/70655/) * [Unify the undo log of all snapshot types](https://github.com/rust-lang/rust/pull/69464/) [§](https://doc.rust-lang.org/stable/releases.html#version-1441-2020-06-18) Version 1.44.1 (2020-06-18) ======================================================================================================= * [rustfmt accepts rustfmt\_skip in cfg\_attr again.](https://github.com/rust-lang/rust/issues/73078) * [Don’t hash executable filenames on apple platforms, fixing backtraces.](https://github.com/rust-lang/cargo/pull/8329) * [Fix crashes when finding backtrace on macOS.](https://github.com/rust-lang/rust/issues/71397) * [Clippy applies lint levels into different files.](https://github.com/rust-lang/rust-clippy/issues/5356) [§](https://doc.rust-lang.org/stable/releases.html#version-1440-2020-06-04) Version 1.44.0 (2020-06-04) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-48) Language ------------------------------------------------------------------------ * [You can now use `async/.await` with `#[no_std]` enabled.](https://github.com/rust-lang/rust/pull/69033/) * [Added the `unused_braces` lint.](https://github.com/rust-lang/rust/pull/70081/) **Syntax-only changes** * [Expansion-driven outline module parsing](https://github.com/rust-lang/rust/pull/69838/) #[cfg(FALSE)] mod foo { mod bar { mod baz; // `foo/bar/baz.rs` doesn't exist, but no error! } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bcfg(FALSE)%5D%0A++++mod+foo+%7B%0A++++++++mod+bar+%7B%0A++++++++++++mod+baz;+//+%60foo/bar/baz.rs%60+doesn%27t+exist,+but+no+error!%0A++++++++%7D%0A++++%7D%0A%7D&edition=2015 "Run code") These are still rejected semantically, so you will likely receive an error but these changes can be seen and parsed by macros and conditional compilation. [§](https://doc.rust-lang.org/stable/releases.html#compiler-48) Compiler ------------------------------------------------------------------------ * [Rustc now respects the `-C codegen-units` flag in incremental mode.](https://github.com/rust-lang/rust/pull/70156/) Additionally when in incremental mode rustc defaults to 256 codegen units. * [Refactored `catch_unwind` to have zero-cost, unless unwinding is enabled and a panic is thrown.](https://github.com/rust-lang/rust/pull/67502/) * [Added tier 3\* support for the `aarch64-unknown-none` and `aarch64-unknown-none-softfloat` targets.](https://github.com/rust-lang/rust/pull/68334/) * [Added tier 3 support for `arm64-apple-tvos` and `x86_64-apple-tvos` targets.](https://github.com/rust-lang/rust/pull/68191/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-48) Libraries -------------------------------------------------------------------------- * [Special cased `vec![]` to map directly to `Vec::new()`.](https://github.com/rust-lang/rust/pull/70632/) This allows `vec![]` to be able to be used in `const` contexts. * [`convert::Infallible` now implements `Hash`.](https://github.com/rust-lang/rust/pull/70281/) * [`OsString` now implements `DerefMut` and `IndexMut` returning a `&mut OsStr`.](https://github.com/rust-lang/rust/pull/70048/) * [Unicode 13 is now supported.](https://github.com/rust-lang/rust/pull/69929/) * [`String` now implements `From<&mut str>`.](https://github.com/rust-lang/rust/pull/69661/) * [`IoSlice` now implements `Copy`.](https://github.com/rust-lang/rust/pull/69403/) * [`Vec` now implements `From<[T; N]>`.](https://github.com/rust-lang/rust/pull/68692/) Where `N` is at most 32. * [`proc_macro::LexError` now implements `fmt::Display` and `Error`.](https://github.com/rust-lang/rust/pull/68899/) * [`from_le_bytes`, `to_le_bytes`, `from_be_bytes`, `to_be_bytes`, `from_ne_bytes`, and `to_ne_bytes` methods are now `const` for all integer types.](https://github.com/rust-lang/rust/pull/69373/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-43) Stabilized APIs -------------------------------------------------------------------------------------- * [`PathBuf::with_capacity`](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.with_capacity) * [`PathBuf::capacity`](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.capacity) * [`PathBuf::clear`](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.clear) * [`PathBuf::reserve`](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.reserve) * [`PathBuf::reserve_exact`](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.reserve_exact) * [`PathBuf::shrink_to_fit`](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.shrink_to_fit) * [`f32::to_int_unchecked`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_int_unchecked) * [`f64::to_int_unchecked`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_int_unchecked) * [`Layout::align_to`](https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.align_to) * [`Layout::pad_to_align`](https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.pad_to_align) * [`Layout::array`](https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.array) * [`Layout::extend`](https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.extend) [§](https://doc.rust-lang.org/stable/releases.html#cargo-46) Cargo ------------------------------------------------------------------ * [Added the `cargo tree` command which will print a tree graph of your dependencies.](https://github.com/rust-lang/cargo/pull/8062/) E.g. mdbook v0.3.2 (/Users/src/rust/mdbook) ├── ammonia v3.0.0 │ ├── html5ever v0.24.0 │ │ ├── log v0.4.8 │ │ │ └── cfg-if v0.1.9 │ │ ├── mac v0.1.1 │ │ └── markup5ever v0.9.0 │ │ ├── log v0.4.8 (*) │ │ ├── phf v0.7.24 │ │ │ └── phf_shared v0.7.24 │ │ │ ├── siphasher v0.2.3 │ │ │ └── unicase v1.4.2 │ │ │ [build-dependencies] │ │ │ └── version_check v0.1.5 ... [](https://play.rust-lang.org/?code=++mdbook+v0.3.2+(/Users/src/rust/mdbook)%0A%E2%94%9C%E2%94%80%E2%94%80+ammonia+v3.0.0%0A%E2%94%82+++%E2%94%9C%E2%94%80%E2%94%80+html5ever+v0.24.0%0A%E2%94%82+++%E2%94%82+++%E2%94%9C%E2%94%80%E2%94%80+log+v0.4.8%0A%E2%94%82+++%E2%94%82+++%E2%94%82+++%E2%94%94%E2%94%80%E2%94%80+cfg-if+v0.1.9%0A%E2%94%82+++%E2%94%82+++%E2%94%9C%E2%94%80%E2%94%80+mac+v0.1.1%0A%E2%94%82+++%E2%94%82+++%E2%94%94%E2%94%80%E2%94%80+markup5ever+v0.9.0%0A%E2%94%82+++%E2%94%82+++++++%E2%94%9C%E2%94%80%E2%94%80+log+v0.4.8+(*)%0A%E2%94%82+++%E2%94%82+++++++%E2%94%9C%E2%94%80%E2%94%80+phf+v0.7.24%0A%E2%94%82+++%E2%94%82+++++++%E2%94%82+++%E2%94%94%E2%94%80%E2%94%80+phf_shared+v0.7.24%0A%E2%94%82+++%E2%94%82+++++++%E2%94%82+++++++%E2%94%9C%E2%94%80%E2%94%80+siphasher+v0.2.3%0A%E2%94%82+++%E2%94%82+++++++%E2%94%82+++++++%E2%94%94%E2%94%80%E2%94%80+unicase+v1.4.2%0A%E2%94%82+++%E2%94%82+++++++%E2%94%82+++++++++++%5Bbuild-dependencies%5D%0A%E2%94%82+++%E2%94%82+++++++%E2%94%82+++++++++++%E2%94%94%E2%94%80%E2%94%80+version_check+v0.1.5%0A...&edition=2015 "Run code") You can also display dependencies on multiple versions of the same crate with `cargo tree -d` (short for `cargo tree --duplicates`). [§](https://doc.rust-lang.org/stable/releases.html#misc-13) Misc ---------------------------------------------------------------- * [Rustdoc now allows you to specify `--crate-version` to have rustdoc include the version in the sidebar.](https://github.com/rust-lang/rust/pull/69494/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-47) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Rustc now correctly generates static libraries on Windows GNU targets with the `.a` extension, rather than the previous `.lib`.](https://github.com/rust-lang/rust/pull/70937/) * [Removed the `-C no_integrated_as` flag from rustc.](https://github.com/rust-lang/rust/pull/70345/) * [The `file_name` property in JSON output of macro errors now points the actual source file rather than the previous format of ``.](https://github.com/rust-lang/rust/pull/70969/) **Note:** this may not point to a file that actually exists on the user’s system. * [The minimum required external LLVM version has been bumped to LLVM 8.](https://github.com/rust-lang/rust/pull/71147/) * [`mem::{zeroed, uninitialised}` will now panic when used with types that do not allow zero initialization such as `NonZeroU8`.](https://github.com/rust-lang/rust/pull/66059/) This was previously a warning. * [In 1.45.0 (the next release) converting a `f64` to `u32` using the `as` operator has been defined as a saturating operation.](https://github.com/rust-lang/rust/pull/71269/) This was previously undefined behaviour, but you can use the `{f64, f32}::to_int_unchecked` methods to continue using the current behaviour, which may be desirable in rare performance sensitive situations. [§](https://doc.rust-lang.org/stable/releases.html#internal-only-6) Internal Only --------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools. * [dep\_graph Avoid allocating a set on when the number reads are small.](https://github.com/rust-lang/rust/pull/69778/) * [Replace big JS dict with JSON parsing.](https://github.com/rust-lang/rust/pull/71250/) [§](https://doc.rust-lang.org/stable/releases.html#version-1431-2020-05-07) Version 1.43.1 (2020-05-07) ======================================================================================================= * [Updated openssl-src to 1.1.1g for CVE-2020-1967.](https://github.com/rust-lang/rust/pull/71430) * [Fixed the stabilization of AVX-512 features.](https://github.com/rust-lang/rust/issues/71473) * [Fixed `cargo package --list` not working with unpublished dependencies.](https://github.com/rust-lang/cargo/issues/8151) [§](https://doc.rust-lang.org/stable/releases.html#version-1430-2020-04-23) Version 1.43.0 (2020-04-23) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-49) Language ------------------------------------------------------------------------ * [Fixed using binary operations with `&{number}` (e.g. `&1.0`) not having the type inferred correctly.](https://github.com/rust-lang/rust/pull/68129/) * [Attributes such as `#[cfg()]` can now be used on `if` expressions.](https://github.com/rust-lang/rust/pull/69201/) **Syntax only changes** * [Allow `type Foo: Ord` syntactically.](https://github.com/rust-lang/rust/pull/69361/) * [Fuse associated and extern items up to defaultness.](https://github.com/rust-lang/rust/pull/69194/) * [Syntactically allow `self` in all `fn` contexts.](https://github.com/rust-lang/rust/pull/68764/) * [Merge `fn` syntax + cleanup item parsing.](https://github.com/rust-lang/rust/pull/68728/) * [`item` macro fragments can be interpolated into `trait`s, `impl`s, and `extern` blocks.](https://github.com/rust-lang/rust/pull/69366/) For example, you may now write: macro_rules! mac_trait { ($i:item) => { trait T { $i } } } mac_trait! { fn foo() {} } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++macro_rules!+mac_trait+%7B%0A++++++++(%24i:item)+=%3E+%7B%0A++++++++++++trait+T+%7B+%24i+%7D%0A++++++++%7D%0A++++%7D%0A++++mac_trait!+%7B%0A++++++++fn+foo()+%7B%7D%0A++++%7D%0A%7D&edition=2015 "Run code") These are still rejected _semantically_, so you will likely receive an error but these changes can be seen and parsed by macros and conditional compilation. [§](https://doc.rust-lang.org/stable/releases.html#compiler-49) Compiler ------------------------------------------------------------------------ * [You can now pass multiple lint flags to rustc to override the previous flags.](https://github.com/rust-lang/rust/pull/67885/) For example; `rustc -D unused -A unused-variables` denies everything in the `unused` lint group except `unused-variables` which is explicitly allowed. However, passing `rustc -A unused-variables -D unused` denies everything in the `unused` lint group **including** `unused-variables` since the allow flag is specified before the deny flag (and therefore overridden). * [rustc will now prefer your system MinGW libraries over its bundled libraries if they are available on `windows-gnu`.](https://github.com/rust-lang/rust/pull/67429/) * [rustc now buffers errors/warnings printed in JSON.](https://github.com/rust-lang/rust/pull/69227/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-49) Libraries -------------------------------------------------------------------------- * [`Arc<[T; N]>`, `Box<[T; N]>`, and `Rc<[T; N]>`, now implement `TryFrom>`,`TryFrom>`, and `TryFrom>` respectively.](https://github.com/rust-lang/rust/pull/69538/) **Note** These conversions are only available when `N` is `0..=32`. * [You can now use associated constants on floats and integers directly, rather than having to import the module.](https://github.com/rust-lang/rust/pull/68952/) e.g. You can now write `u32::MAX` or `f32::NAN` with no imports. * [`u8::is_ascii` is now `const`.](https://github.com/rust-lang/rust/pull/68984/) * [`String` now implements `AsMut`.](https://github.com/rust-lang/rust/pull/68742/) * [Added the `primitive` module to `std` and `core`.](https://github.com/rust-lang/rust/pull/67637/) This module reexports Rust’s primitive types. This is mainly useful in macros where you want avoid these types being shadowed. * [Relaxed some of the trait bounds on `HashMap` and `HashSet`.](https://github.com/rust-lang/rust/pull/67642/) * [`string::FromUtf8Error` now implements `Clone + Eq`.](https://github.com/rust-lang/rust/pull/68738/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-44) Stabilized APIs -------------------------------------------------------------------------------------- * [`Once::is_completed`](https://doc.rust-lang.org/std/sync/struct.Once.html#method.is_completed) * [`f32::LOG10_2`](https://doc.rust-lang.org/std/f32/consts/constant.LOG10_2.html) * [`f32::LOG2_10`](https://doc.rust-lang.org/std/f32/consts/constant.LOG2_10.html) * [`f64::LOG10_2`](https://doc.rust-lang.org/std/f64/consts/constant.LOG10_2.html) * [`f64::LOG2_10`](https://doc.rust-lang.org/std/f64/consts/constant.LOG2_10.html) * [`iter::once_with`](https://doc.rust-lang.org/std/iter/fn.once_with.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-47) Cargo ------------------------------------------------------------------ * [You can now set config `[profile]`s in your `.cargo/config`, or through your environment.](https://github.com/rust-lang/cargo/pull/7823) * [Cargo will now set `CARGO_BIN_EXE_` pointing to a binary’s executable path when running integration tests or benchmarks.](https://github.com/rust-lang/cargo/pull/7697) `` is the name of your binary as-is e.g. If you wanted the executable path for a binary named `my-program`you would use `env!("CARGO_BIN_EXE_my-program")`. [§](https://doc.rust-lang.org/stable/releases.html#misc-14) Misc ---------------------------------------------------------------- * [Certain checks in the `const_err` lint were deemed unrelated to const evaluation](https://github.com/rust-lang/rust/pull/69185/) , and have been moved to the `unconditional_panic` and `arithmetic_overflow` lints. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-48) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Having trailing syntax in the `assert!` macro is now a hard error.](https://github.com/rust-lang/rust/pull/69548/) This has been a warning since 1.36.0. * [Fixed `Self` not having the correctly inferred type.](https://github.com/rust-lang/rust/pull/69340) This incorrectly led to some instances being accepted, and now correctly emits a hard error. [§](https://doc.rust-lang.org/stable/releases.html#internal-only-7) Internal Only --------------------------------------------------------------------------------- These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of `rustc` and related tools. * [All components are now built with `opt-level=3` instead of `2`.](https://github.com/rust-lang/rust/pull/67878/) * [Improved how rustc generates drop code.](https://github.com/rust-lang/rust/pull/67332/) * [Improved performance from `#[inline]`\-ing certain hot functions.](https://github.com/rust-lang/rust/pull/69256/) * [traits: preallocate 2 Vecs of known initial size](https://github.com/rust-lang/rust/pull/69022/) * [Avoid exponential behaviour when relating types](https://github.com/rust-lang/rust/pull/68772/) * [Skip `Drop` terminators for enum variants without drop glue](https://github.com/rust-lang/rust/pull/68943/) * [Improve performance of coherence checks](https://github.com/rust-lang/rust/pull/68966/) * [Deduplicate types in the generator witness](https://github.com/rust-lang/rust/pull/68672/) * [Invert control in struct\_lint\_level.](https://github.com/rust-lang/rust/pull/68725/) [§](https://doc.rust-lang.org/stable/releases.html#version-1420-2020-03-12) Version 1.42.0 (2020-03-12) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-50) Language ------------------------------------------------------------------------ * [You can now use the slice pattern syntax with subslices.](https://github.com/rust-lang/rust/pull/67712/) e.g. fn foo(words: &[&str]) { match words { ["Hello", "World", "!", ..] => println!("Hello World!"), ["Foo", "Bar", ..] => println!("Baz"), rest => println!("{:?}", rest), } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+foo(words:+%26%5B%26str%5D)+%7B%0A++++++++match+words+%7B%0A++++++++++++%5B%22Hello%22,+%22World%22,+%22!%22,+..%5D+=%3E+println!(%22Hello+World!%22),%0A++++++++++++%5B%22Foo%22,+%22Bar%22,+..%5D+=%3E+println!(%22Baz%22),%0A++++++++++++rest+=%3E+println!(%22%7B:?%7D%22,+rest),%0A++++++++%7D%0A++++%7D%0A%7D&edition=2015 "Run code") * [You can now use `#[repr(transparent)]` on univariant `enum`s.](https://github.com/rust-lang/rust/pull/68122/) Meaning that you can create an enum that has the exact layout and ABI of the type it contains. * [You can now use outer attribute procedural macros on inline modules.](https://github.com/rust-lang/rust/pull/64273/) * [There are some _syntax-only_ changes:](https://github.com/rust-lang/rust/pull/67131/) * `default` is syntactically allowed before items in `trait` definitions. * Items in `impl`s (i.e. `const`s, `type`s, and `fn`s) may syntactically leave out their bodies in favor of `;`. * Bounds on associated types in `impl`s are now syntactically allowed (e.g. `type Foo: Ord;`). * `...` (the C-variadic type) may occur syntactically directly as the type of any function parameter. These are still rejected _semantically_, so you will likely receive an error but these changes can be seen and parsed by procedural macros and conditional compilation. [§](https://doc.rust-lang.org/stable/releases.html#compiler-50) Compiler ------------------------------------------------------------------------ * [Added tier 2\* support for `armv7a-none-eabi`.](https://github.com/rust-lang/rust/pull/68253/) * [Added tier 2 support for `riscv64gc-unknown-linux-gnu`.](https://github.com/rust-lang/rust/pull/68339/) * [`Option::{expect,unwrap}` and `Result::{expect, expect_err, unwrap, unwrap_err}` now produce panic messages pointing to the location where they were called, rather than `core`’s internals.](https://github.com/rust-lang/rust/pull/67887/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-50) Libraries -------------------------------------------------------------------------- * [`iter::Empty` now implements `Send` and `Sync` for any `T`.](https://github.com/rust-lang/rust/pull/68348/) * [`Pin::{map_unchecked, map_unchecked_mut}` no longer require the return type to implement `Sized`.](https://github.com/rust-lang/rust/pull/67935/) * [`io::Cursor` now derives `PartialEq` and `Eq`.](https://github.com/rust-lang/rust/pull/67233/) * [`Layout::new` is now `const`.](https://github.com/rust-lang/rust/pull/66254/) * [Added Standard Library support for `riscv64gc-unknown-linux-gnu`.](https://github.com/rust-lang/rust/pull/66899/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-45) Stabilized APIs -------------------------------------------------------------------------------------- * [`CondVar::wait_while`](https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait_while) * [`CondVar::wait_timeout_while`](https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait_timeout_while) * [`DebugMap::key`](https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html#method.key) * [`DebugMap::value`](https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html#method.value) * [`ManuallyDrop::take`](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html#method.take) * [`matches!`](https://doc.rust-lang.org/stable/std/macro.matches.html) * [`ptr::slice_from_raw_parts_mut`](https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts_mut.html) * [`ptr::slice_from_raw_parts`](https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-48) Cargo ------------------------------------------------------------------ * [You no longer need to include `extern crate proc_macro;` to be able to `use proc_macro;` in the `2018` edition.](https://github.com/rust-lang/cargo/pull/7700) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-49) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`Error::description` has been deprecated, and its use will now produce a warning.](https://github.com/rust-lang/rust/pull/66919/) It’s recommended to use `Display`/`to_string` instead. [§](https://doc.rust-lang.org/stable/releases.html#version-1411-2020-02-27) Version 1.41.1 (2020-02-27) ======================================================================================================= * [Always check types of static items](https://github.com/rust-lang/rust/pull/69145) * [Always check lifetime bounds of `Copy` impls](https://github.com/rust-lang/rust/pull/69145) * [Fix miscompilation in callers of `Layout::repeat`](https://github.com/rust-lang/rust/issues/69225) * [Rust 1.41.0 was announced as the last Rust release with tier 1 or tier 2 support for 32-bit Apple targets](https://blog.rust-lang.org/2020/01/03/reducing-support-for-32-bit-apple-targets.html) . That announcement did not expect a patch release. 1.41.1 also includes release binaries for these targets. [§](https://doc.rust-lang.org/stable/releases.html#version-1410-2020-01-30) Version 1.41.0 (2020-01-30) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-51) Language ------------------------------------------------------------------------ * [You can now pass type parameters to foreign items when implementing traits.](https://github.com/rust-lang/rust/pull/65879/) E.g. You can now write `impl From for Vec {}`. * [You can now arbitrarily nest receiver types in the `self` position.](https://github.com/rust-lang/rust/pull/64325/) E.g. you can now write `fn foo(self: Box>) {}`. Previously only `Self`, `&Self`, `&mut Self`, `Arc`, `Rc`, and `Box` were allowed. * [You can now use any valid identifier in a `format_args` macro.](https://github.com/rust-lang/rust/pull/66847/) Previously identifiers starting with an underscore were not allowed. * [Visibility modifiers (e.g. `pub`) are now syntactically allowed on trait items and enum variants.](https://github.com/rust-lang/rust/pull/66183/) These are still rejected semantically, but can be seen and parsed by procedural macros and conditional compilation. * [You can now define a Rust `extern "C"` function with `Box` and use `T*` as the corresponding type on the C side.](https://github.com/rust-lang/rust/pull/62514/) Please see [the documentation](https://doc.rust-lang.org/std/boxed/index.html#memory-layout) for more information, including the important caveat about preferring to avoid `Box` in Rust signatures for functions defined in C. [§](https://doc.rust-lang.org/stable/releases.html#compiler-51) Compiler ------------------------------------------------------------------------ * [Rustc will now warn if you have unused loop `'label`s.](https://github.com/rust-lang/rust/pull/66325/) * [Removed support for the `i686-unknown-dragonfly` target.](https://github.com/rust-lang/rust/pull/67255/) * [Added tier 3 support\* for the `riscv64gc-unknown-linux-gnu` target.](https://github.com/rust-lang/rust/pull/66661/) * [You can now pass an arguments file passing the `@path` syntax to rustc.](https://github.com/rust-lang/rust/pull/66172/) Note that the format differs somewhat from what is found in other tooling; please see [the documentation](https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#path-load-command-line-flags-from-a-path) for more information. * [You can now provide `--extern` flag without a path, indicating that it is available from the search path or specified with an `-L` flag.](https://github.com/rust-lang/rust/pull/64882/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-51) Libraries -------------------------------------------------------------------------- * [The `core::panic` module is now stable.](https://github.com/rust-lang/rust/pull/66771/) It was already stable through `std`. * [`NonZero*` numerics now implement `From` if it’s a smaller integer width.](https://github.com/rust-lang/rust/pull/66277/) E.g. `NonZeroU16` now implements `From`. * [`MaybeUninit` now implements `fmt::Debug`.](https://github.com/rust-lang/rust/pull/65013/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-46) Stabilized APIs -------------------------------------------------------------------------------------- * [`Result::map_or`](https://doc.rust-lang.org/std/result/enum.Result.html#method.map_or) * [`Result::map_or_else`](https://doc.rust-lang.org/std/result/enum.Result.html#method.map_or_else) * [`std::rc::Weak::weak_count`](https://doc.rust-lang.org/std/rc/struct.Weak.html#method.weak_count) * [`std::rc::Weak::strong_count`](https://doc.rust-lang.org/std/rc/struct.Weak.html#method.strong_count) * [`std::sync::Weak::weak_count`](https://doc.rust-lang.org/std/sync/struct.Weak.html#method.weak_count) * [`std::sync::Weak::strong_count`](https://doc.rust-lang.org/std/sync/struct.Weak.html#method.strong_count) [§](https://doc.rust-lang.org/stable/releases.html#cargo-49) Cargo ------------------------------------------------------------------ * [Cargo will now document all the private items for binary crates by default.](https://github.com/rust-lang/cargo/pull/7593/) * [`cargo-install` will now reinstall the package if it detects that it is out of date.](https://github.com/rust-lang/cargo/pull/7560/) * [Cargo.lock now uses a more git friendly format that should help to reduce merge conflicts.](https://github.com/rust-lang/cargo/pull/7579/) * [You can now override specific dependencies’s build settings](https://github.com/rust-lang/cargo/pull/7591/) E.g. `[profile.dev.package.image] opt-level = 2` sets the `image` crate’s optimisation level to `2` for debug builds. You can also use `[profile..build-override]` to override build scripts and their dependencies. [§](https://doc.rust-lang.org/stable/releases.html#misc-15) Misc ---------------------------------------------------------------- * [You can now specify `edition` in documentation code blocks to compile the block for that edition.](https://github.com/rust-lang/rust/pull/66238/) E.g. `edition2018` tells rustdoc that the code sample should be compiled the 2018 edition of Rust. * [You can now provide custom themes to rustdoc with `--theme`, and check the current theme with `--check-theme`.](https://github.com/rust-lang/rust/pull/54733/) * [You can use `#[cfg(doc)]` to compile an item when building documentation.](https://github.com/rust-lang/rust/pull/61351/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-50) Compatibility Notes ---------------------------------------------------------------------------------------------- * [As previously announced 1.41 will be the last tier 1 release for 32-bit Apple targets.](https://blog.rust-lang.org/2020/01/03/reducing-support-for-32-bit-apple-targets.html) This means that the source code is still available to build, but the targets are no longer being tested and release binaries for those platforms will no longer be distributed by the Rust project. Please refer to the linked blog post for more information. [§](https://doc.rust-lang.org/stable/releases.html#version-1400-2019-12-19) Version 1.40.0 (2019-12-19) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-52) Language ------------------------------------------------------------------------ * [You can now use tuple `struct`s and tuple `enum` variant’s constructors in `const` contexts.](https://github.com/rust-lang/rust/pull/65188/) e.g. pub struct Point(i32, i32); const ORIGIN: Point = { let constructor = Point; constructor(0, 0) }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++pub+struct+Point(i32,+i32);%0A++++%0A++++const+ORIGIN:+Point+=+%7B%0A++++++++let+constructor+=+Point;%0A++++%0A++++++++constructor(0,+0)%0A++++%7D;%0A%7D&edition=2015 "Run code") * [You can now mark `struct`s, `enum`s, and `enum` variants with the `#[non_exhaustive]` attribute to indicate that there may be variants or fields added in the future.](https://github.com/rust-lang/rust/pull/64639/) For example this requires adding a wild-card branch (`_ => {}`) to any match statements on a non-exhaustive `enum`. [(RFC 2008)](https://rust-lang.github.io/rfcs/2008-non-exhaustive.html) * [You can now use function-like procedural macros in `extern` blocks and in type positions.](https://github.com/rust-lang/rust/pull/63931/) e.g. `type Generated = macro!();` * [Function-like and attribute procedural macros can now emit `macro_rules!` items, so you can now have your macros generate macros.](https://github.com/rust-lang/rust/pull/64035/) * [The `meta` pattern matcher in `macro_rules!` now correctly matches the modern attribute syntax.](https://github.com/rust-lang/rust/pull/63674/) For example `(#[$m:meta])` now matches `#[attr]`, `#[attr{tokens}]`, `#[attr[tokens]]`, and `#[attr(tokens)]`. [§](https://doc.rust-lang.org/stable/releases.html#compiler-52) Compiler ------------------------------------------------------------------------ * [Added tier 3 support\* for the `thumbv7neon-unknown-linux-musleabihf` target.](https://github.com/rust-lang/rust/pull/66103/) * [Added tier 3 support for the `aarch64-unknown-none-softfloat` target.](https://github.com/rust-lang/rust/pull/64589/) * [Added tier 3 support for the `mips64-unknown-linux-muslabi64`, and `mips64el-unknown-linux-muslabi64` targets.](https://github.com/rust-lang/rust/pull/65843/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-52) Libraries -------------------------------------------------------------------------- * [The `is_power_of_two` method on unsigned numeric types is now a `const` function.](https://github.com/rust-lang/rust/pull/65092/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-47) Stabilized APIs -------------------------------------------------------------------------------------- * [`BTreeMap::get_key_value`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.get_key_value) * [`HashMap::get_key_value`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.get_key_value) * [`Option::as_deref_mut`](https://doc.rust-lang.org/std/option/enum.Option.html#method.as_deref_mut) * [`Option::as_deref`](https://doc.rust-lang.org/std/option/enum.Option.html#method.as_deref) * [`Option::flatten`](https://doc.rust-lang.org/std/option/enum.Option.html#method.flatten) * [`UdpSocket::peer_addr`](https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.peer_addr) * [`f32::to_be_bytes`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_be_bytes) * [`f32::to_le_bytes`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_le_bytes) * [`f32::to_ne_bytes`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_ne_bytes) * [`f64::to_be_bytes`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_be_bytes) * [`f64::to_le_bytes`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_le_bytes) * [`f64::to_ne_bytes`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_ne_bytes) * [`f32::from_be_bytes`](https://doc.rust-lang.org/std/primitive.f32.html#method.from_be_bytes) * [`f32::from_le_bytes`](https://doc.rust-lang.org/std/primitive.f32.html#method.from_le_bytes) * [`f32::from_ne_bytes`](https://doc.rust-lang.org/std/primitive.f32.html#method.from_ne_bytes) * [`f64::from_be_bytes`](https://doc.rust-lang.org/std/primitive.f64.html#method.from_be_bytes) * [`f64::from_le_bytes`](https://doc.rust-lang.org/std/primitive.f64.html#method.from_le_bytes) * [`f64::from_ne_bytes`](https://doc.rust-lang.org/std/primitive.f64.html#method.from_ne_bytes) * [`mem::take`](https://doc.rust-lang.org/std/mem/fn.take.html) * [`slice::repeat`](https://doc.rust-lang.org/std/primitive.slice.html#method.repeat) * [`todo!`](https://doc.rust-lang.org/std/macro.todo.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-50) Cargo ------------------------------------------------------------------ * [Cargo will now always display warnings, rather than only on fresh builds.](https://github.com/rust-lang/cargo/pull/7450/) * [Feature flags (except `--all-features`) passed to a virtual workspace will now produce an error.](https://github.com/rust-lang/cargo/pull/7507/) Previously these flags were ignored. * [You can now publish `dev-dependencies` without including a `version`.](https://github.com/rust-lang/cargo/pull/7333/) [§](https://doc.rust-lang.org/stable/releases.html#misc-16) Misc ---------------------------------------------------------------- * [You can now specify the `#[cfg(doctest)]` attribute to include an item only when running documentation tests with `rustdoc`.](https://github.com/rust-lang/rust/pull/63803/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-51) Compatibility Notes ---------------------------------------------------------------------------------------------- * [As previously announced, any previous NLL warnings in the 2015 edition are now hard errors.](https://github.com/rust-lang/rust/pull/64221/) * [The `include!` macro will now warn if it failed to include the entire file.](https://github.com/rust-lang/rust/pull/64284/) The `include!` macro unintentionally only includes the first _expression_ in a file, and this can be unintuitive. This will become either a hard error in a future release, or the behavior may be fixed to include all expressions as expected. * [Using `#[inline]` on function prototypes and consts now emits a warning under `unused_attribute` lint.](https://github.com/rust-lang/rust/pull/65294/) Using `#[inline]` anywhere else inside traits or `extern` blocks now correctly emits a hard error. [§](https://doc.rust-lang.org/stable/releases.html#version-1390-2019-11-07) Version 1.39.0 (2019-11-07) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-53) Language ------------------------------------------------------------------------ * [You can now create `async` functions and blocks with `async fn`, `async move {}`, and `async {}` respectively, and you can now call `.await` on async expressions.](https://github.com/rust-lang/rust/pull/63209/) * [You can now use certain attributes on function, closure, and function pointer parameters.](https://github.com/rust-lang/rust/pull/64010/) These attributes include `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, `forbid` as well as inert helper attributes used by procedural macro attributes applied to items. e.g. fn len( #[cfg(windows)] slice: &[u16], #[cfg(not(windows))] slice: &[u8], ) -> usize { slice.len() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+len(%0A++++++++%23%5Bcfg(windows)%5D+slice:+%26%5Bu16%5D,%0A++++++++%23%5Bcfg(not(windows))%5D+slice:+%26%5Bu8%5D,%0A++++)+-%3E+usize+%7B%0A++++++++slice.len()%0A++++%7D%0A%7D&edition=2015 "Run code") * [You can now take shared references to bind-by-move patterns in the `if` guards of `match` arms.](https://github.com/rust-lang/rust/pull/63118/) e.g. fn main() { let array: Box<[u8; 4]> = Box::new([1, 2, 3, 4]); match array { nums // ---- `nums` is bound by move. if nums.iter().sum::() == 10 // ^------ `.iter()` implicitly takes a reference to `nums`. => { drop(nums); // ----------- Legal as `nums` was bound by move and so we have ownership. } _ => unreachable!(), } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+array:+Box%3C%5Bu8;+4%5D%3E+=+Box::new(%5B1,+2,+3,+4%5D);%0A%0A++++match+array+%7B%0A++++++++nums%0A//++++++----+%60nums%60+is+bound+by+move.%0A++++++++++++if+nums.iter().sum::%3Cu8%3E()+==+10%0A//+++++++++++++++++%5E------+%60.iter()%60+implicitly+takes+a+reference+to+%60nums%60.%0A++++++++=%3E+%7B%0A++++++++++++drop(nums);%0A//++++++++++-----------+Legal+as+%60nums%60+was+bound+by+move+and+so+we+have+ownership.%0A++++++++%7D%0A++++++++_+=%3E+unreachable!(),%0A++++%7D%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-53) Compiler ------------------------------------------------------------------------ * [Added tier 3\* support for the `i686-unknown-uefi` target.](https://github.com/rust-lang/rust/pull/64334/) * [Added tier 3 support for the `sparc64-unknown-openbsd` target.](https://github.com/rust-lang/rust/pull/63595/) * [rustc will now trim code snippets in diagnostics to fit in your terminal.](https://github.com/rust-lang/rust/pull/63402/) **Note** Cargo currently doesn’t use this feature. Refer to [cargo#7315](https://github.com/rust-lang/cargo/pull/7315/) to track this feature’s progress. * [You can now pass `--show-output` argument to test binaries to print the output of successful tests.](https://github.com/rust-lang/rust/pull/62600/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-53) Libraries -------------------------------------------------------------------------- * [`Vec::new` and `String::new` are now `const` functions.](https://github.com/rust-lang/rust/pull/64028/) * [`LinkedList::new` is now a `const` function.](https://github.com/rust-lang/rust/pull/63684/) * [`str::len`, `[T]::len` and `str::as_bytes` are now `const` functions.](https://github.com/rust-lang/rust/pull/63770/) * [The `abs`, `wrapping_abs`, and `overflowing_abs` numeric functions are now `const`.](https://github.com/rust-lang/rust/pull/63786/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-48) Stabilized APIs -------------------------------------------------------------------------------------- * [`Pin::into_inner`](https://doc.rust-lang.org/std/pin/struct.Pin.html#method.into_inner) * [`Instant::checked_duration_since`](https://doc.rust-lang.org/std/time/struct.Instant.html#method.checked_duration_since) * [`Instant::saturating_duration_since`](https://doc.rust-lang.org/std/time/struct.Instant.html#method.saturating_duration_since) [§](https://doc.rust-lang.org/stable/releases.html#cargo-51) Cargo ------------------------------------------------------------------ * [You can now publish git dependencies if supplied with a `version`.](https://github.com/rust-lang/cargo/pull/7237/) * [The `--all` flag has been renamed to `--workspace`.](https://github.com/rust-lang/cargo/pull/7241/) Using `--all` is now deprecated. [§](https://doc.rust-lang.org/stable/releases.html#misc-17) Misc ---------------------------------------------------------------- * [You can now pass `-Clinker` to rustdoc to control the linker used for compiling doctests.](https://github.com/rust-lang/rust/pull/63834/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-52) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Code that was previously accepted by the old borrow checker, but rejected by the NLL borrow checker is now a hard error in Rust 2018.](https://github.com/rust-lang/rust/pull/63565/) This was previously a warning, and will also become a hard error in the Rust 2015 edition in the 1.40.0 release. * [`rustdoc` now requires `rustc` to be installed and in the same directory to run tests.](https://github.com/rust-lang/rust/pull/63827/) This should improve performance when running a large amount of doctests. * [The `try!` macro will now issue a deprecation warning.](https://github.com/rust-lang/rust/pull/62672/) It is recommended to use the `?` operator instead. * [`asinh(-0.0)` now correctly returns `-0.0`.](https://github.com/rust-lang/rust/pull/63698/) Previously this returned `0.0`. [§](https://doc.rust-lang.org/stable/releases.html#version-1380-2019-09-26) Version 1.38.0 (2019-09-26) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-54) Language ------------------------------------------------------------------------ * [The `#[global_allocator]` attribute can now be used in submodules.](https://github.com/rust-lang/rust/pull/62735/) * [The `#[deprecated]` attribute can now be used on macros.](https://github.com/rust-lang/rust/pull/62042/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-54) Compiler ------------------------------------------------------------------------ * [Added pipelined compilation support to `rustc`.](https://github.com/rust-lang/rust/pull/62766/) This will improve compilation times in some cases. For further information please refer to the [_“Evaluating pipelined rustc compilation”_](https://internals.rust-lang.org/t/evaluating-pipelined-rustc-compilation/10199) thread. * [Added tier 3\* support for the `aarch64-uwp-windows-msvc`, `i686-uwp-windows-gnu`, `i686-uwp-windows-msvc`, `x86_64-uwp-windows-gnu`, and `x86_64-uwp-windows-msvc` targets.](https://github.com/rust-lang/rust/pull/60260/) * [Added tier 3 support for the `armv7-unknown-linux-gnueabi` and `armv7-unknown-linux-musleabi` targets.](https://github.com/rust-lang/rust/pull/63107/) * [Added tier 3 support for the `hexagon-unknown-linux-musl` target.](https://github.com/rust-lang/rust/pull/62814/) * [Added tier 3 support for the `riscv32i-unknown-none-elf` target.](https://github.com/rust-lang/rust/pull/62784/) * [Upgraded to LLVM 9.](https://github.com/rust-lang/rust/pull/62592/) \* Refer to Rust’s [platform support page](https://doc.rust-lang.org/rustc/platform-support.html) for more information on Rust’s tiered platform support. [§](https://doc.rust-lang.org/stable/releases.html#libraries-54) Libraries -------------------------------------------------------------------------- * [`ascii::EscapeDefault` now implements `Clone` and `Display`.](https://github.com/rust-lang/rust/pull/63421/) * [Derive macros for prelude traits (e.g. `Clone`, `Debug`, `Hash`) are now available at the same path as the trait.](https://github.com/rust-lang/rust/pull/63056/) (e.g. The `Clone` derive macro is available at `std::clone::Clone`). This also makes all built-in macros available in `std`/`core` root. e.g. `std::include_bytes!`. * [`str::Chars` now implements `Debug`.](https://github.com/rust-lang/rust/pull/63000/) * [`slice::{concat, connect, join}` now accepts `&[T]` in addition to `&T`.](https://github.com/rust-lang/rust/pull/62528/) * [`*const T` and `*mut T` now implement `marker::Unpin`.](https://github.com/rust-lang/rust/pull/62583/) * [`Arc<[T]>` and `Rc<[T]>` now implement `FromIterator`.](https://github.com/rust-lang/rust/pull/61953/) * [Added euclidean remainder and division operations (`div_euclid`, `rem_euclid`) to all numeric primitives.](https://github.com/rust-lang/rust/pull/61884/) Additionally `checked`, `overflowing`, and `wrapping` versions are available for all integer primitives. * [`thread::AccessError` now implements `Clone`, `Copy`, `Eq`, `Error`, and `PartialEq`.](https://github.com/rust-lang/rust/pull/61491/) * [`iter::{StepBy, Peekable, Take}` now implement `DoubleEndedIterator`.](https://github.com/rust-lang/rust/pull/61457/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-49) Stabilized APIs -------------------------------------------------------------------------------------- * [`<*const T>::cast`](https://doc.rust-lang.org/std/primitive.pointer.html#method.cast) * [`<*mut T>::cast`](https://doc.rust-lang.org/std/primitive.pointer.html#method.cast) * [`Duration::as_secs_f32`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs_f32) * [`Duration::as_secs_f64`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs_f64) * [`Duration::div_f32`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.div_f32) * [`Duration::div_f64`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.div_f64) * [`Duration::from_secs_f32`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_secs_f32) * [`Duration::from_secs_f64`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_secs_f64) * [`Duration::mul_f32`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.mul_f32) * [`Duration::mul_f64`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.mul_f64) * [`any::type_name`](https://doc.rust-lang.org/std/any/fn.type_name.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-52) Cargo ------------------------------------------------------------------ * [Added pipelined compilation support to `cargo`.](https://github.com/rust-lang/cargo/pull/7143/) * [You can now pass the `--features` option multiple times to enable multiple features.](https://github.com/rust-lang/cargo/pull/7084/) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-25) Rustdoc ---------------------------------------------------------------------- * [Documentation on `pub use` statements is prepended to the documentation of the re-exported item](https://github.com/rust-lang/rust/pull/63048) [§](https://doc.rust-lang.org/stable/releases.html#misc-18) Misc ---------------------------------------------------------------- * [`rustc` will now warn about some incorrect uses of `mem::{uninitialized, zeroed}` that are known to cause undefined behaviour.](https://github.com/rust-lang/rust/pull/63346/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-53) Compatibility Notes ---------------------------------------------------------------------------------------------- * The [`x86_64-unknown-uefi` platform can not be built](https://github.com/rust-lang/rust/issues/62785/) with rustc 1.38.0. * The [`armv7-unknown-linux-gnueabihf` platform is known to have issues](https://github.com/rust-lang/rust/issues/62896/) with certain crates such as libc. [§](https://doc.rust-lang.org/stable/releases.html#version-1370-2019-08-15) Version 1.37.0 (2019-08-15) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-55) Language ------------------------------------------------------------------------ * `#[must_use]` will now warn if the type is contained in a [tuple](https://github.com/rust-lang/rust/pull/61100/) , [`Box`](https://github.com/rust-lang/rust/pull/62228/) , or an [array](https://github.com/rust-lang/rust/pull/62235/) and unused. * [You can now use the `cfg` and `cfg_attr` attributes on generic parameters.](https://github.com/rust-lang/rust/pull/61547/) * [You can now use enum variants through type alias.](https://github.com/rust-lang/rust/pull/61682/) e.g. You can write the following: type MyOption = Option; fn increment_or_zero(x: MyOption) -> u8 { match x { MyOption::Some(y) => y + 1, MyOption::None => 0, } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++type+MyOption+=+Option%3Cu8%3E;%0A++++%0A++++fn+increment_or_zero(x:+MyOption)+-%3E+u8+%7B%0A++++++++match+x+%7B%0A++++++++++++MyOption::Some(y)+=%3E+y+%2B+1,%0A++++++++++++MyOption::None+=%3E+0,%0A++++++++%7D%0A++++%7D%0A%7D&edition=2015 "Run code") * [You can now use `_` as an identifier for consts.](https://github.com/rust-lang/rust/pull/61347/) e.g. You can write `const _: u32 = 5;`. * [You can now use `#[repr(align(X)]` on enums.](https://github.com/rust-lang/rust/pull/61229/) * [The `?` Kleene macro operator is now available in the 2015 edition.](https://github.com/rust-lang/rust/pull/60932/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-55) Compiler ------------------------------------------------------------------------ * [You can now enable Profile-Guided Optimization with the `-C profile-generate` and `-C profile-use` flags.](https://github.com/rust-lang/rust/pull/61268/) For more information on how to use profile guided optimization, please refer to the [rustc book](https://doc.rust-lang.org/rustc/profile-guided-optimization.html) . * [The `rust-lldb` wrapper script should now work again.](https://github.com/rust-lang/rust/pull/61827/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-55) Libraries -------------------------------------------------------------------------- * [`mem::MaybeUninit` is now ABI-compatible with `T`.](https://github.com/rust-lang/rust/pull/61802/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-50) Stabilized APIs -------------------------------------------------------------------------------------- * [`BufReader::buffer`](https://doc.rust-lang.org/std/io/struct.BufReader.html#method.buffer) * [`BufWriter::buffer`](https://doc.rust-lang.org/std/io/struct.BufWriter.html#method.buffer) * [`Cell::from_mut`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.from_mut) * [`Cell<[T]>::as_slice_of_cells`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.as_slice_of_cells) * [`DoubleEndedIterator::nth_back`](https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.nth_back) * [`Option::xor`](https://doc.rust-lang.org/std/option/enum.Option.html#method.xor) * [`Wrapping::reverse_bits`](https://doc.rust-lang.org/std/num/struct.Wrapping.html#method.reverse_bits) * [`i128::reverse_bits`](https://doc.rust-lang.org/std/primitive.i128.html#method.reverse_bits) * [`i16::reverse_bits`](https://doc.rust-lang.org/std/primitive.i16.html#method.reverse_bits) * [`i32::reverse_bits`](https://doc.rust-lang.org/std/primitive.i32.html#method.reverse_bits) * [`i64::reverse_bits`](https://doc.rust-lang.org/std/primitive.i64.html#method.reverse_bits) * [`i8::reverse_bits`](https://doc.rust-lang.org/std/primitive.i8.html#method.reverse_bits) * [`isize::reverse_bits`](https://doc.rust-lang.org/std/primitive.isize.html#method.reverse_bits) * [`slice::copy_within`](https://doc.rust-lang.org/std/primitive.slice.html#method.copy_within) * [`u128::reverse_bits`](https://doc.rust-lang.org/std/primitive.u128.html#method.reverse_bits) * [`u16::reverse_bits`](https://doc.rust-lang.org/std/primitive.u16.html#method.reverse_bits) * [`u32::reverse_bits`](https://doc.rust-lang.org/std/primitive.u32.html#method.reverse_bits) * [`u64::reverse_bits`](https://doc.rust-lang.org/std/primitive.u64.html#method.reverse_bits) * [`u8::reverse_bits`](https://doc.rust-lang.org/std/primitive.u8.html#method.reverse_bits) * [`usize::reverse_bits`](https://doc.rust-lang.org/std/primitive.usize.html#method.reverse_bits) [§](https://doc.rust-lang.org/stable/releases.html#cargo-53) Cargo ------------------------------------------------------------------ * [`Cargo.lock` files are now included by default when publishing executable crates with executables.](https://github.com/rust-lang/cargo/pull/7026/) * [You can now specify `default-run="foo"` in `[package]` to specify the default executable to use for `cargo run`.](https://github.com/rust-lang/cargo/pull/7056/) [§](https://doc.rust-lang.org/stable/releases.html#misc-19) Misc ---------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-54) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Using `...` for inclusive range patterns will now warn by default.](https://github.com/rust-lang/rust/pull/61342/) Please transition your code to using the `..=` syntax for inclusive ranges instead. * [Using a trait object without the `dyn` will now warn by default.](https://github.com/rust-lang/rust/pull/61203/) Please transition your code to use `dyn Trait` for trait objects instead. [§](https://doc.rust-lang.org/stable/releases.html#version-1360-2019-07-04) Version 1.36.0 (2019-07-04) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-56) Language ------------------------------------------------------------------------ * [Non-Lexical Lifetimes are now enabled on the 2015 edition.](https://github.com/rust-lang/rust/pull/59114/) * [The order of traits in trait objects no longer affects the semantics of that object.](https://github.com/rust-lang/rust/pull/59445/) e.g. `dyn Send + fmt::Debug` is now equivalent to `dyn fmt::Debug + Send`, where this was previously not the case. [§](https://doc.rust-lang.org/stable/releases.html#libraries-56) Libraries -------------------------------------------------------------------------- * [`HashMap`’s implementation has been replaced with `hashbrown::HashMap` implementation.](https://github.com/rust-lang/rust/pull/58623/) * [`TryFromSliceError` now implements `From`.](https://github.com/rust-lang/rust/pull/60318/) * [`mem::needs_drop` is now available as a const fn.](https://github.com/rust-lang/rust/pull/60364/) * [`alloc::Layout::from_size_align_unchecked` is now available as a const fn.](https://github.com/rust-lang/rust/pull/60370/) * [`String` now implements `BorrowMut`.](https://github.com/rust-lang/rust/pull/60404/) * [`io::Cursor` now implements `Default`.](https://github.com/rust-lang/rust/pull/60234/) * [Both `NonNull::{dangling, cast}` are now const fns.](https://github.com/rust-lang/rust/pull/60244/) * [The `alloc` crate is now stable.](https://github.com/rust-lang/rust/pull/59675/) `alloc` allows you to use a subset of `std` (e.g. `Vec`, `Box`, `Arc`) in `#![no_std]` environments if the environment has access to heap memory allocation. * [`String` now implements `From<&String>`.](https://github.com/rust-lang/rust/pull/59825/) * [You can now pass multiple arguments to the `dbg!` macro.](https://github.com/rust-lang/rust/pull/59826/) `dbg!` will return a tuple of each argument when there is multiple arguments. * [`Result::{is_err, is_ok}` are now `#[must_use]` and will produce a warning if not used.](https://github.com/rust-lang/rust/pull/59648/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-51) Stabilized APIs -------------------------------------------------------------------------------------- * [`VecDeque::rotate_left`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.rotate_left) * [`VecDeque::rotate_right`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.rotate_right) * [`Iterator::copied`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.copied) * [`io::IoSlice`](https://doc.rust-lang.org/std/io/struct.IoSlice.html) * [`io::IoSliceMut`](https://doc.rust-lang.org/std/io/struct.IoSliceMut.html) * [`Read::read_vectored`](https://doc.rust-lang.org/std/io/trait.Read.html#method.read_vectored) * [`Write::write_vectored`](https://doc.rust-lang.org/std/io/trait.Write.html#method.write_vectored) * [`str::as_mut_ptr`](https://doc.rust-lang.org/std/primitive.str.html#method.as_mut_ptr) * [`mem::MaybeUninit`](https://doc.rust-lang.org/std/mem/union.MaybeUninit.html) * [`pointer::align_offset`](https://doc.rust-lang.org/std/primitive.pointer.html#method.align_offset) * [`future::Future`](https://doc.rust-lang.org/std/future/trait.Future.html) * [`task::Context`](https://doc.rust-lang.org/beta/std/task/struct.Context.html) * [`task::RawWaker`](https://doc.rust-lang.org/beta/std/task/struct.RawWaker.html) * [`task::RawWakerVTable`](https://doc.rust-lang.org/beta/std/task/struct.RawWakerVTable.html) * [`task::Waker`](https://doc.rust-lang.org/beta/std/task/struct.Waker.html) * [`task::Poll`](https://doc.rust-lang.org/beta/std/task/enum.Poll.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-54) Cargo ------------------------------------------------------------------ * [Cargo will now produce an error if you attempt to use the name of a required dependency as a feature.](https://github.com/rust-lang/cargo/pull/6860/) * [You can now pass the `--offline` flag to run cargo without accessing the network.](https://github.com/rust-lang/cargo/pull/6934/) You can find further change’s in [Cargo’s 1.36.0 release notes](https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-136-2019-07-04) . [§](https://doc.rust-lang.org/stable/releases.html#clippy-1) Clippy ------------------------------------------------------------------- There have been numerous additions and fixes to clippy, see [Clippy’s 1.36.0 release notes](https://github.com/rust-lang/rust-clippy/blob/master/CHANGELOG.md#rust-136) for more details. [§](https://doc.rust-lang.org/stable/releases.html#misc-20) Misc ---------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-55) Compatibility Notes ---------------------------------------------------------------------------------------------- * With the stabilisation of `mem::MaybeUninit`, `mem::uninitialized` use is no longer recommended, and will be deprecated in 1.39.0. [§](https://doc.rust-lang.org/stable/releases.html#version-1350-2019-05-23) Version 1.35.0 (2019-05-23) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-57) Language ------------------------------------------------------------------------ * [`FnOnce`, `FnMut`, and the `Fn` traits are now implemented for `Box`, `Box`, and `Box` respectively.](https://github.com/rust-lang/rust/pull/59500/) * [You can now coerce closures into unsafe function pointers.](https://github.com/rust-lang/rust/pull/59580/) e.g. unsafe fn call_unsafe(func: unsafe fn()) { func() } pub fn main() { unsafe { call_unsafe(|| {}); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Aunsafe+fn+call_unsafe(func:+unsafe+fn())+%7B%0A++++func()%0A%7D%0A%0Apub+fn+main()+%7B%0A++++unsafe+%7B+call_unsafe(%7C%7C+%7B%7D);+%7D%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-56) Compiler ------------------------------------------------------------------------ * [Added the `armv6-unknown-freebsd-gnueabihf` and `armv7-unknown-freebsd-gnueabihf` targets.](https://github.com/rust-lang/rust/pull/58080/) * [Added the `wasm32-unknown-wasi` target.](https://github.com/rust-lang/rust/pull/59464/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-57) Libraries -------------------------------------------------------------------------- * [`Thread` will now show its ID in `Debug` output.](https://github.com/rust-lang/rust/pull/59460/) * [`StdinLock`, `StdoutLock`, and `StderrLock` now implement `AsRawFd`.](https://github.com/rust-lang/rust/pull/59512/) * [`alloc::System` now implements `Default`.](https://github.com/rust-lang/rust/pull/59451/) * [Expanded `Debug` output (`{:#?}`) for structs now has a trailing comma on the last field.](https://github.com/rust-lang/rust/pull/59076/) * [`char::{ToLowercase, ToUppercase}` now implement `ExactSizeIterator`.](https://github.com/rust-lang/rust/pull/58778/) * [All `NonZero` numeric types now implement `FromStr`.](https://github.com/rust-lang/rust/pull/58717/) * [Removed the `Read` trait bounds on the `BufReader::{get_ref, get_mut, into_inner}` methods.](https://github.com/rust-lang/rust/pull/58423/) * [You can now call the `dbg!` macro without any parameters to print the file and line where it is called.](https://github.com/rust-lang/rust/pull/57847/) * [In place ASCII case conversions are now up to 4× faster.](https://github.com/rust-lang/rust/pull/59283/) e.g. `str::make_ascii_lowercase` * [`hash_map::{OccupiedEntry, VacantEntry}` now implement `Sync` and `Send`.](https://github.com/rust-lang/rust/pull/58369/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-52) Stabilized APIs -------------------------------------------------------------------------------------- * [`f32::copysign`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.copysign) * [`f64::copysign`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.copysign) * [`RefCell::replace_with`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.replace_with) * [`RefCell::map_split`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.map_split) * [`ptr::hash`](https://doc.rust-lang.org/stable/std/ptr/fn.hash.html) * [`Range::contains`](https://doc.rust-lang.org/std/ops/struct.Range.html#method.contains) * [`RangeFrom::contains`](https://doc.rust-lang.org/std/ops/struct.RangeFrom.html#method.contains) * [`RangeTo::contains`](https://doc.rust-lang.org/std/ops/struct.RangeTo.html#method.contains) * [`RangeInclusive::contains`](https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html#method.contains) * [`RangeToInclusive::contains`](https://doc.rust-lang.org/std/ops/struct.RangeToInclusive.html#method.contains) * [`Option::copied`](https://doc.rust-lang.org/std/option/enum.Option.html#method.copied) [§](https://doc.rust-lang.org/stable/releases.html#cargo-55) Cargo ------------------------------------------------------------------ * [You can now set `cargo:rustc-cdylib-link-arg` at build time to pass custom linker arguments when building a `cdylib`.](https://github.com/rust-lang/cargo/pull/6298/) Its usage is highly platform specific. [§](https://doc.rust-lang.org/stable/releases.html#misc-21) Misc ---------------------------------------------------------------- * [The Rust toolchain is now available natively for musl based distros.](https://github.com/rust-lang/rust/pull/58575) [§](https://doc.rust-lang.org/stable/releases.html#version-1342-2019-05-14) Version 1.34.2 (2019-05-14) ======================================================================================================= * [Destabilize the `Error::type_id` function due to a security vulnerability](https://github.com/rust-lang/rust/pull/60785) ([CVE-2019-12083](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-12083) ) [§](https://doc.rust-lang.org/stable/releases.html#version-1341-2019-04-25) Version 1.34.1 (2019-04-25) ======================================================================================================= * [Fix false positives for the `redundant_closure` Clippy lint](https://github.com/rust-lang/rust-clippy/pull/3821) * [Fix false positives for the `missing_const_for_fn` Clippy lint](https://github.com/rust-lang/rust-clippy/pull/3844) * [Fix Clippy panic when checking some macros](https://github.com/rust-lang/rust-clippy/pull/3805) [§](https://doc.rust-lang.org/stable/releases.html#version-1340-2019-04-11) Version 1.34.0 (2019-04-11) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-58) Language ------------------------------------------------------------------------ * [You can now use `#[deprecated = "reason"]`](https://github.com/rust-lang/rust/pull/58166/) as a shorthand for `#[deprecated(note = "reason")]`. This was previously allowed by mistake but had no effect. * [You can now accept token streams in `#[attr()]`,`#[attr[]]`, and `#[attr{}]` procedural macros.](https://github.com/rust-lang/rust/pull/57367/) * [You can now write `extern crate self as foo;`](https://github.com/rust-lang/rust/pull/57407/) to import your crate’s root into the extern prelude. [§](https://doc.rust-lang.org/stable/releases.html#compiler-57) Compiler ------------------------------------------------------------------------ * [You can now target `riscv64imac-unknown-none-elf` and `riscv64gc-unknown-none-elf`.](https://github.com/rust-lang/rust/pull/58406/) * [You can now enable linker plugin LTO optimisations with `-C linker-plugin-lto`.](https://github.com/rust-lang/rust/pull/58057/) This allows rustc to compile your Rust code into LLVM bitcode allowing LLVM to perform LTO optimisations across C/C++ FFI boundaries. * [You can now target `powerpc64-unknown-freebsd`.](https://github.com/rust-lang/rust/pull/57809/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-58) Libraries -------------------------------------------------------------------------- * [The trait bounds have been removed on some of `HashMap`’s and `HashSet`’s basic methods.](https://github.com/rust-lang/rust/pull/58370/) Most notably you no longer require the `Hash` trait to create an iterator. * [The `Ord` trait bounds have been removed on some of `BinaryHeap`’s basic methods.](https://github.com/rust-lang/rust/pull/58421/) Most notably you no longer require the `Ord` trait to create an iterator. * [The methods `overflowing_neg` and `wrapping_neg` are now `const` functions for all numeric types.](https://github.com/rust-lang/rust/pull/58044/) * [Indexing a `str` is now generic over all types that implement `SliceIndex`.](https://github.com/rust-lang/rust/pull/57604/) * [`str::trim`, `str::trim_matches`, `str::trim_{start, end}`, and `str::trim_{start, end}_matches` are now `#[must_use]`](https://github.com/rust-lang/rust/pull/57106/) and will produce a warning if their returning type is unused. * [The methods `checked_pow`, `saturating_pow`, `wrapping_pow`, and `overflowing_pow` are now available for all numeric types.](https://github.com/rust-lang/rust/pull/57873/) These are equivalent to methods such as `wrapping_add` for the `pow` operation. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-53) Stabilized APIs -------------------------------------------------------------------------------------- #### [§](https://doc.rust-lang.org/stable/releases.html#std--core) std & core * [`Any::type_id`](https://doc.rust-lang.org/std/any/trait.Any.html#tymethod.type_id) * [`Error::type_id`](https://doc.rust-lang.org/std/error/trait.Error.html#method.type_id) * [`atomic::AtomicI16`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI16.html) * [`atomic::AtomicI32`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI32.html) * [`atomic::AtomicI64`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI64.html) * [`atomic::AtomicI8`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI8.html) * [`atomic::AtomicU16`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU16.html) * [`atomic::AtomicU32`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.html) * [`atomic::AtomicU64`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU64.html) * [`atomic::AtomicU8`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU8.html) * [`convert::Infallible`](https://doc.rust-lang.org/std/convert/enum.Infallible.html) * [`convert::TryFrom`](https://doc.rust-lang.org/std/convert/trait.TryFrom.html) * [`convert::TryInto`](https://doc.rust-lang.org/std/convert/trait.TryInto.html) * [`iter::from_fn`](https://doc.rust-lang.org/std/iter/fn.from_fn.html) * [`iter::successors`](https://doc.rust-lang.org/std/iter/fn.successors.html) * [`num::NonZeroI128`](https://doc.rust-lang.org/std/num/struct.NonZeroI128.html) * [`num::NonZeroI16`](https://doc.rust-lang.org/std/num/struct.NonZeroI16.html) * [`num::NonZeroI32`](https://doc.rust-lang.org/std/num/struct.NonZeroI32.html) * [`num::NonZeroI64`](https://doc.rust-lang.org/std/num/struct.NonZeroI64.html) * [`num::NonZeroI8`](https://doc.rust-lang.org/std/num/struct.NonZeroI8.html) * [`num::NonZeroIsize`](https://doc.rust-lang.org/std/num/struct.NonZeroIsize.html) * [`slice::sort_by_cached_key`](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_cached_key) * [`str::escape_debug`](https://doc.rust-lang.org/std/primitive.str.html#method.escape_debug) * [`str::escape_default`](https://doc.rust-lang.org/std/primitive.str.html#method.escape_default) * [`str::escape_unicode`](https://doc.rust-lang.org/std/primitive.str.html#method.escape_unicode) * [`str::split_ascii_whitespace`](https://doc.rust-lang.org/std/primitive.str.html#method.split_ascii_whitespace) #### [§](https://doc.rust-lang.org/stable/releases.html#std) std * [`Instant::checked_add`](https://doc.rust-lang.org/std/time/struct.Instant.html#method.checked_add) * [`Instant::checked_sub`](https://doc.rust-lang.org/std/time/struct.Instant.html#method.checked_sub) * [`SystemTime::checked_add`](https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.checked_add) * [`SystemTime::checked_sub`](https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.checked_sub) [§](https://doc.rust-lang.org/stable/releases.html#cargo-56) Cargo ------------------------------------------------------------------ * [You can now use alternative registries to crates.io.](https://github.com/rust-lang/cargo/pull/6654/) [§](https://doc.rust-lang.org/stable/releases.html#misc-22) Misc ---------------------------------------------------------------- * [You can now use the `?` operator in your documentation tests without manually adding `fn main() -> Result<(), _> {}`.](https://github.com/rust-lang/rust/pull/56470/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-56) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`Command::before_exec` is being replaced by the unsafe method `Command::pre_exec`](https://github.com/rust-lang/rust/pull/58059/) and will be deprecated with Rust 1.37.0. * [Use of `ATOMIC_{BOOL, ISIZE, USIZE}_INIT` is now deprecated](https://github.com/rust-lang/rust/pull/57425/) as you can now use `const` functions in `static` variables. [§](https://doc.rust-lang.org/stable/releases.html#version-1330-2019-02-28) Version 1.33.0 (2019-02-28) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-59) Language ------------------------------------------------------------------------ * [You can now use the `cfg(target_vendor)` attribute.](https://github.com/rust-lang/rust/pull/57465/) E.g. `#[cfg(target_vendor="apple")] fn main() { println!("Hello Apple!"); }` * [Integer patterns such as in a match expression can now be exhaustive.](https://github.com/rust-lang/rust/pull/56362) E.g. You can have match statement on a `u8` that covers `0..=255` and you would no longer be required to have a `_ => unreachable!()` case. * [You can now have multiple patterns in `if let` and `while let` expressions.](https://github.com/rust-lang/rust/pull/57532/) You can do this with the same syntax as a `match` expression. E.g. enum Creature { Crab(String), Lobster(String), Person(String), } fn main() { let state = Creature::Crab("Ferris"); if let Creature::Crab(name) | Creature::Person(name) = state { println!("This creature's name is: {}", name); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Aenum+Creature+%7B%0A++++Crab(String),%0A++++Lobster(String),%0A++++Person(String),%0A%7D%0A%0Afn+main()+%7B%0A++++let+state+=+Creature::Crab(%22Ferris%22);%0A%0A++++if+let+Creature::Crab(name)+%7C+Creature::Person(name)+=+state+%7B%0A++++++++println!(%22This+creature%27s+name+is:+%7B%7D%22,+name);%0A++++%7D%0A%7D&edition=2015 "Run code") * [You can now have irrefutable `if let` and `while let` patterns.](https://github.com/rust-lang/rust/pull/57535/) Using this feature will by default produce a warning as this behaviour can be unintuitive. E.g. `if let _ = 5 {}` * [You can now use `let` bindings, assignments, expression statements, and irrefutable pattern destructuring in const functions.](https://github.com/rust-lang/rust/pull/57175/) * [You can now call unsafe const functions.](https://github.com/rust-lang/rust/pull/57067/) E.g. const unsafe fn foo() -> i32 { 5 } const fn bar() -> i32 { unsafe { foo() } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++const+unsafe+fn+foo()+-%3E+i32+%7B+5+%7D%0A++++const+fn+bar()+-%3E+i32+%7B%0A++++++++unsafe+%7B+foo()+%7D%0A++++%7D%0A%7D&edition=2015 "Run code") * [You can now specify multiple attributes in a `cfg_attr` attribute.](https://github.com/rust-lang/rust/pull/57332/) E.g. `#[cfg_attr(all(), must_use, optimize)]` * [You can now specify a specific alignment with the `#[repr(packed)]` attribute.](https://github.com/rust-lang/rust/pull/57049/) E.g. `#[repr(packed(2))] struct Foo(i16, i32);` is a struct with an alignment of 2 bytes and a size of 6 bytes. * [You can now import an item from a module as an `_`.](https://github.com/rust-lang/rust/pull/56303/) This allows you to import a trait’s impls, and not have the name in the namespace. E.g. use std::io::Read as _; // Allowed as there is only one `Read` in the module. pub trait Read {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io::Read+as+_;%0A++++%0A++++//+Allowed+as+there+is+only+one+%60Read%60+in+the+module.%0A++++pub+trait+Read+%7B%7D%0A%7D&edition=2015 "Run code") * [You may now use `Rc`, `Arc`, and `Pin` as method receivers](https://github.com/rust-lang/rust/pull/56805) . [§](https://doc.rust-lang.org/stable/releases.html#compiler-58) Compiler ------------------------------------------------------------------------ * [You can now set a linker flavor for `rustc` with the `-Clinker-flavor` command line argument.](https://github.com/rust-lang/rust/pull/56351/) * [The minimum required LLVM version has been bumped to 6.0.](https://github.com/rust-lang/rust/pull/56642/) * [Added support for the PowerPC64 architecture on FreeBSD.](https://github.com/rust-lang/rust/pull/57615/) * [The `x86_64-fortanix-unknown-sgx` target support has been upgraded to tier 2 support.](https://github.com/rust-lang/rust/pull/57130/) Visit the [platform support](https://forge.rust-lang.org/platform-support.html) page for information on Rust’s platform support. * [Added support for the `thumbv7neon-linux-androideabi` and `thumbv7neon-unknown-linux-gnueabihf` targets.](https://github.com/rust-lang/rust/pull/56947/) * [Added support for the `x86_64-unknown-uefi` target.](https://github.com/rust-lang/rust/pull/56769/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-59) Libraries -------------------------------------------------------------------------- * [The methods `overflowing_{add, sub, mul, shl, shr}` are now `const` functions for all numeric types.](https://github.com/rust-lang/rust/pull/57566/) * [The methods `rotate_left`, `rotate_right`, and `wrapping_{add, sub, mul, shl, shr}` are now `const` functions for all numeric types.](https://github.com/rust-lang/rust/pull/57105) * [The methods `is_positive` and `is_negative` are now `const` functions for all signed numeric types.](https://github.com/rust-lang/rust/pull/57105) * [The `get` method for all `NonZero` types is now `const`.](https://github.com/rust-lang/rust/pull/57167/) * [The methods `count_ones`, `count_zeros`, `leading_zeros`, `trailing_zeros`, `swap_bytes`, `from_be`, `from_le`, `to_be`, `to_le` are now `const` for all numeric types.](https://github.com/rust-lang/rust/pull/57234/) * [`Ipv4Addr::new` is now a `const` function](https://github.com/rust-lang/rust/pull/57234/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-54) Stabilized APIs -------------------------------------------------------------------------------------- * [`unix::FileExt::read_exact_at`](https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#method.read_exact_at) * [`unix::FileExt::write_all_at`](https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#method.write_all_at) * [`Option::transpose`](https://doc.rust-lang.org/std/option/enum.Option.html#method.transpose) * [`Result::transpose`](https://doc.rust-lang.org/std/result/enum.Result.html#method.transpose) * [`convert::identity`](https://doc.rust-lang.org/std/convert/fn.identity.html) * [`pin::Pin`](https://doc.rust-lang.org/std/pin/struct.Pin.html) * [`marker::Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html) * [`marker::PhantomPinned`](https://doc.rust-lang.org/nightly/std/marker/struct.PhantomPinned.html) * [`Vec::resize_with`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize_with) * [`VecDeque::resize_with`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.resize_with) * [`Duration::as_millis`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_millis) * [`Duration::as_micros`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_micros) * [`Duration::as_nanos`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_nanos) [§](https://doc.rust-lang.org/stable/releases.html#cargo-57) Cargo ------------------------------------------------------------------ * [You can now publish crates that require a feature flag to compile with `cargo publish --features` or `cargo publish --all-features`.](https://github.com/rust-lang/cargo/pull/6453/) * [Cargo should now rebuild a crate if a file was modified during the initial build.](https://github.com/rust-lang/cargo/pull/6484/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-57) Compatibility Notes ---------------------------------------------------------------------------------------------- * The methods `str::{trim_left, trim_right, trim_left_matches, trim_right_matches}` are now deprecated in the standard library, and their usage will now produce a warning. Please use the `str::{trim_start, trim_end, trim_start_matches, trim_end_matches}` methods instead. * The `Error::cause` method has been deprecated in favor of `Error::source` which supports downcasting. * [Libtest no longer creates a new thread for each test when `--test-threads=1`. It also runs the tests in deterministic order](https://github.com/rust-lang/rust/pull/56243) [§](https://doc.rust-lang.org/stable/releases.html#version-1320-2019-01-17) Version 1.32.0 (2019-01-17) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-60) Language ------------------------------------------------------------------------ #### [§](https://doc.rust-lang.org/stable/releases.html#2018-edition) 2018 edition * [You can now use the `?` operator in macro definitions.](https://github.com/rust-lang/rust/pull/56245/) The `?` operator allows you to specify zero or one repetitions similar to the `*` and `+` operators. * [Module paths with no leading keyword like `super`, `self`, or `crate`, will now always resolve to the item (`enum`, `struct`, etc.) available in the module if present, before resolving to a external crate or an item the prelude.](https://github.com/rust-lang/rust/pull/56759/) E.g. enum Color { Red, Green, Blue } use Color::*; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+Color+%7B+Red,+Green,+Blue+%7D%0A++++%0A++++use+Color::*;%0A%7D&edition=2015 "Run code") #### [§](https://doc.rust-lang.org/stable/releases.html#all-editions) All editions * [You can now match against `PhantomData` types.](https://github.com/rust-lang/rust/pull/55837/) * [You can now match against literals in macros with the `literal` specifier.](https://github.com/rust-lang/rust/pull/56072/) This will match against a literal of any type. E.g. `1`, `'A'`, `"Hello World"` * [Self can now be used as a constructor and pattern for unit and tuple structs.](https://github.com/rust-lang/rust/pull/56365/) E.g. struct Point(i32, i32); impl Point { pub fn new(x: i32, y: i32) -> Self { Self(x, y) } pub fn is_origin(&self) -> bool { match self { Self(0, 0) => true, _ => false, } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Point(i32,+i32);%0A++++%0A++++impl+Point+%7B%0A++++++++pub+fn+new(x:+i32,+y:+i32)+-%3E+Self+%7B%0A++++++++++++Self(x,+y)%0A++++++++%7D%0A++++%0A++++++++pub+fn+is_origin(%26self)+-%3E+bool+%7B%0A++++++++++++match+self+%7B%0A++++++++++++++++Self(0,+0)+=%3E+true,%0A++++++++++++++++_+=%3E+false,%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2015 "Run code") * [Self can also now be used in type definitions.](https://github.com/rust-lang/rust/pull/56366/) E.g. enum List where Self: PartialOrd // can write `Self` instead of `List` { Nil, Cons(T, Box) // likewise here } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+List%3CT%3E%0A++++where%0A++++++++Self:+PartialOrd%3CSelf%3E+//+can+write+%60Self%60+instead+of+%60List%3CT%3E%60%0A++++%7B%0A++++++++Nil,%0A++++++++Cons(T,+Box%3CSelf%3E)+//+likewise+here%0A++++%7D%0A%7D&edition=2015 "Run code") * [You can now mark traits with `#[must_use]`.](https://github.com/rust-lang/rust/pull/55663/) This provides a warning if a `impl Trait` or `dyn Trait` is returned and unused in the program. [§](https://doc.rust-lang.org/stable/releases.html#compiler-59) Compiler ------------------------------------------------------------------------ * [The default allocator has changed from jemalloc to the default allocator on your system.](https://github.com/rust-lang/rust/pull/55238/) The compiler itself on Linux & macOS will still use jemalloc, but programs compiled with it will use the system allocator. * [Added the `aarch64-pc-windows-msvc` target.](https://github.com/rust-lang/rust/pull/55702/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-60) Libraries -------------------------------------------------------------------------- * [`PathBuf` now implements `FromStr`.](https://github.com/rust-lang/rust/pull/55148/) * [`Box<[T]>` now implements `FromIterator`.](https://github.com/rust-lang/rust/pull/55843/) * [The `dbg!` macro has been stabilized.](https://github.com/rust-lang/rust/pull/56395/) This macro enables you to easily debug expressions in your rust program. E.g. let a = 2; let b = dbg!(a * 2) + 1; // ^-- prints: [src/main.rs:4] a * 2 = 4 assert_eq!(b, 5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+2;%0A++++let+b+=+dbg!(a+*+2)+%2B+1;%0A++++//++++++%5E--+prints:+%5Bsrc/main.rs:4%5D+a+*+2+=+4%0A++++assert_eq!(b,+5);%0A%7D&edition=2015 "Run code") The following APIs are now `const` functions and can be used in a `const` context. * [`Cell::as_ptr`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.as_ptr) * [`UnsafeCell::get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get) * [`char::is_ascii`](https://doc.rust-lang.org/std/primitive.char.html#method.is_ascii) * [`iter::empty`](https://doc.rust-lang.org/std/iter/fn.empty.html) * [`ManuallyDrop::new`](https://doc.rust-lang.org/std/mem/struct.ManuallyDrop.html#method.new) * [`ManuallyDrop::into_inner`](https://doc.rust-lang.org/std/mem/struct.ManuallyDrop.html#method.into_inner) * [`RangeInclusive::start`](https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html#method.start) * [`RangeInclusive::end`](https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html#method.end) * [`NonNull::as_ptr`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_ptr) * [`slice::as_ptr`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr) * [`str::as_ptr`](https://doc.rust-lang.org/std/primitive.str.html#method.as_ptr) * [`Duration::as_secs`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.as_secs) * [`Duration::subsec_millis`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_millis) * [`Duration::subsec_micros`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_micros) * [`Duration::subsec_nanos`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_nanos) * [`CStr::as_ptr`](https://doc.rust-lang.org/std/ffi/struct.CStr.html#method.as_ptr) * [`Ipv4Addr::is_unspecified`](https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html#method.is_unspecified) * [`Ipv6Addr::new`](https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.new) * [`Ipv6Addr::octets`](https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.octets) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-55) Stabilized APIs -------------------------------------------------------------------------------------- * [`i8::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.to_be_bytes) * [`i8::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.to_le_bytes) * [`i8::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.to_ne_bytes) * [`i8::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.from_be_bytes) * [`i8::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.from_le_bytes) * [`i8::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i8.html#method.from_ne_bytes) * [`i16::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.to_be_bytes) * [`i16::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.to_le_bytes) * [`i16::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.to_ne_bytes) * [`i16::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.from_be_bytes) * [`i16::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.from_le_bytes) * [`i16::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i16.html#method.from_ne_bytes) * [`i32::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_be_bytes) * [`i32::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_le_bytes) * [`i32::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_ne_bytes) * [`i32::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.from_be_bytes) * [`i32::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.from_le_bytes) * [`i32::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i32.html#method.from_ne_bytes) * [`i64::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.to_be_bytes) * [`i64::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.to_le_bytes) * [`i64::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.to_ne_bytes) * [`i64::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.from_be_bytes) * [`i64::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.from_le_bytes) * [`i64::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i64.html#method.from_ne_bytes) * [`i128::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.to_be_bytes) * [`i128::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.to_le_bytes) * [`i128::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.to_ne_bytes) * [`i128::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.from_be_bytes) * [`i128::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.from_le_bytes) * [`i128::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.i128.html#method.from_ne_bytes) * [`isize::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.to_be_bytes) * [`isize::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.to_le_bytes) * [`isize::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.to_ne_bytes) * [`isize::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.from_be_bytes) * [`isize::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.from_le_bytes) * [`isize::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.isize.html#method.from_ne_bytes) * [`u8::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_be_bytes) * [`u8::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_le_bytes) * [`u8::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.to_ne_bytes) * [`u8::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.from_be_bytes) * [`u8::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.from_le_bytes) * [`u8::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u8.html#method.from_ne_bytes) * [`u16::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.to_be_bytes) * [`u16::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.to_le_bytes) * [`u16::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.to_ne_bytes) * [`u16::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.from_be_bytes) * [`u16::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.from_le_bytes) * [`u16::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u16.html#method.from_ne_bytes) * [`u32::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.to_be_bytes) * [`u32::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.to_le_bytes) * [`u32::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.to_ne_bytes) * [`u32::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.from_be_bytes) * [`u32::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.from_le_bytes) * [`u32::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.from_ne_bytes) * [`u64::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.to_be_bytes) * [`u64::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.to_le_bytes) * [`u64::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.to_ne_bytes) * [`u64::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.from_be_bytes) * [`u64::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.from_le_bytes) * [`u64::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u64.html#method.from_ne_bytes) * [`u128::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.to_be_bytes) * [`u128::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.to_le_bytes) * [`u128::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.to_ne_bytes) * [`u128::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.from_be_bytes) * [`u128::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.from_le_bytes) * [`u128::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.u128.html#method.from_ne_bytes) * [`usize::to_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.to_be_bytes) * [`usize::to_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.to_le_bytes) * [`usize::to_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.to_ne_bytes) * [`usize::from_be_bytes`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.from_be_bytes) * [`usize::from_le_bytes`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.from_le_bytes) * [`usize::from_ne_bytes`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.from_ne_bytes) [§](https://doc.rust-lang.org/stable/releases.html#cargo-58) Cargo ------------------------------------------------------------------ * [You can now run `cargo c` as an alias for `cargo check`.](https://github.com/rust-lang/cargo/pull/6218/) * [Usernames are now allowed in alt registry URLs.](https://github.com/rust-lang/cargo/pull/6242/) [§](https://doc.rust-lang.org/stable/releases.html#misc-23) Misc ---------------------------------------------------------------- * [`libproc_macro` has been added to the `rust-src` distribution.](https://github.com/rust-lang/rust/pull/55280/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-58) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The argument types for AVX’s `_mm256_stream_si256`, `_mm256_stream_pd`, `_mm256_stream_ps`](https://github.com/rust-lang/rust/pull/55610/) have been changed from `*const` to `*mut` as the previous implementation was unsound. [§](https://doc.rust-lang.org/stable/releases.html#version-1311-2018-12-20) Version 1.31.1 (2018-12-20) ======================================================================================================= * [Fix Rust failing to build on `powerpc-unknown-netbsd`](https://github.com/rust-lang/rust/pull/56562) * [Fix broken go-to-definition in RLS](https://github.com/rust-lang/rls/issues/1171) * [Fix infinite loop on hover in RLS](https://github.com/rust-lang/rls/pull/1170) [§](https://doc.rust-lang.org/stable/releases.html#version-1310-2018-12-06) Version 1.31.0 (2018-12-06) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-61) Language ------------------------------------------------------------------------ * 🎉 [This version marks the release of the 2018 edition of Rust.](https://github.com/rust-lang/rust/pull/54057/) 🎉 * [New lifetime elision rules now allow for eliding lifetimes in functions and impl headers.](https://github.com/rust-lang/rust/pull/54778/) E.g. `impl<'a> Reader for BufReader<'a> {}` can now be `impl Reader for BufReader<'_> {}`. Lifetimes are still required to be defined in structs. * [You can now define and use `const` functions.](https://github.com/rust-lang/rust/pull/54835/) These are currently a strict minimal subset of the [const fn RFC](https://github.com/rust-lang/rfcs/pull/911) . Refer to the [language reference](https://doc.rust-lang.org/reference/items/functions.html#const-functions) for what exactly is available. * [You can now use tool lints, which allow you to scope lints from external tools using attributes.](https://github.com/rust-lang/rust/pull/54870/) E.g. `#[allow(clippy::filter_map)]`. * [`#[no_mangle]` and `#[export_name]` attributes can now be located anywhere in a crate, not just in exported functions.](https://github.com/rust-lang/rust/pull/54451/) * [You can now use parentheses in pattern matches.](https://github.com/rust-lang/rust/pull/54497/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-60) Compiler ------------------------------------------------------------------------ * [Updated musl to 1.1.20](https://github.com/rust-lang/rust/pull/54430/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-61) Libraries -------------------------------------------------------------------------- * [You can now convert `num::NonZero*` types to their raw equivalents using the `From` trait.](https://github.com/rust-lang/rust/pull/54240/) E.g. `u8` now implements `From`. * [You can now convert a `&Option` into `Option<&T>` and `&mut Option` into `Option<&mut T>` using the `From` trait.](https://github.com/rust-lang/rust/pull/53218/) * [You can now multiply (`*`) a `time::Duration` by a `u32`.](https://github.com/rust-lang/rust/pull/52813/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-56) Stabilized APIs -------------------------------------------------------------------------------------- * [`slice::align_to`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to) * [`slice::align_to_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to_mut) * [`slice::chunks_exact`](https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact) * [`slice::chunks_exact_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact_mut) * [`slice::rchunks`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks) * [`slice::rchunks_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_mut) * [`slice::rchunks_exact`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_exact) * [`slice::rchunks_exact_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_mut) * [`Option::replace`](https://doc.rust-lang.org/std/option/enum.Option.html#method.replace) [§](https://doc.rust-lang.org/stable/releases.html#cargo-59) Cargo ------------------------------------------------------------------ * [Cargo will now download crates in parallel using HTTP/2.](https://github.com/rust-lang/cargo/pull/6005/) * [You can now rename packages in your Cargo.toml](https://github.com/rust-lang/cargo/pull/6319/) We have a guide on [how to use the `package` key in your dependencies.](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml) [§](https://doc.rust-lang.org/stable/releases.html#version-1301-2018-11-08) Version 1.30.1 (2018-11-08) ======================================================================================================= * [Fixed overflow ICE in rustdoc](https://github.com/rust-lang/rust/pull/54199) * [Cap Cargo progress bar width at 60 in MSYS terminals](https://github.com/rust-lang/cargo/pull/6122) [§](https://doc.rust-lang.org/stable/releases.html#version-1300-2018-10-25) Version 1.30.0 (2018-10-25) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-62) Language ------------------------------------------------------------------------ * [Procedural macros are now available.](https://github.com/rust-lang/rust/pull/52081/) These kinds of macros allow for more powerful code generation. There is a [new chapter available](https://doc.rust-lang.org/nightly/book/2018-edition/ch19-06-macros.html) in the Rust Programming Language book that goes further in depth. * [You can now use keywords as identifiers using the raw identifiers syntax (`r#`),](https://github.com/rust-lang/rust/pull/53236/) e.g. `let r#for = true;` * [Using anonymous parameters in traits is now deprecated with a warning and will be a hard error in the 2018 edition.](https://github.com/rust-lang/rust/pull/53272/) * [You can now use `crate` in paths.](https://github.com/rust-lang/rust/pull/54404/) This allows you to refer to the crate root in the path, e.g. `use crate::foo;` refers to `foo` in `src/lib.rs`. * [Using a external crate no longer requires being prefixed with `::`.](https://github.com/rust-lang/rust/pull/54404/) Previously, using a external crate in a module without a use statement required `let json = ::serde_json::from_str(foo);` but can now be written as `let json = serde_json::from_str(foo);`. * [You can now apply the `#[used]` attribute to static items to prevent the compiler from optimising them away, even if they appear to be unused,](https://github.com/rust-lang/rust/pull/51363/) e.g. `#[used] static FOO: u32 = 1;` * [You can now import and reexport macros from other crates with the `use` syntax.](https://github.com/rust-lang/rust/pull/50911/) Macros exported with `#[macro_export]` are now placed into the root module of the crate. If your macro relies on calling other local macros, it is recommended to export with the `#[macro_export(local_inner_macros)]` attribute so users won’t have to import those macros. * [You can now catch visibility keywords (e.g. `pub`, `pub(crate)`) in macros using the `vis` specifier.](https://github.com/rust-lang/rust/pull/53370/) * [Non-macro attributes now allow all forms of literals, not just strings.](https://github.com/rust-lang/rust/pull/53044/) Previously, you would write `#[attr("true")]`, and you can now write `#[attr(true)]`. * [You can now specify a function to handle a panic in the Rust runtime with the `#[panic_handler]` attribute.](https://github.com/rust-lang/rust/pull/51366/) [§](https://doc.rust-lang.org/stable/releases.html#compiler-61) Compiler ------------------------------------------------------------------------ * [Added the `riscv32imc-unknown-none-elf` target.](https://github.com/rust-lang/rust/pull/53822/) * [Added the `aarch64-unknown-netbsd` target](https://github.com/rust-lang/rust/pull/53165/) * [Upgraded to LLVM 8.](https://github.com/rust-lang/rust/pull/53611/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-62) Libraries -------------------------------------------------------------------------- * [`ManuallyDrop` now allows the inner type to be unsized.](https://github.com/rust-lang/rust/pull/53033/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-57) Stabilized APIs -------------------------------------------------------------------------------------- * [`Ipv4Addr::BROADCAST`](https://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#associatedconstant.BROADCAST) * [`Ipv4Addr::LOCALHOST`](https://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#associatedconstant.LOCALHOST) * [`Ipv4Addr::UNSPECIFIED`](https://doc.rust-lang.org/nightly/std/net/struct.Ipv4Addr.html#associatedconstant.UNSPECIFIED) * [`Ipv6Addr::LOCALHOST`](https://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#associatedconstant.LOCALHOST) * [`Ipv6Addr::UNSPECIFIED`](https://doc.rust-lang.org/nightly/std/net/struct.Ipv6Addr.html#associatedconstant.UNSPECIFIED) * [`Iterator::find_map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find_map) The following methods are replacement methods for `trim_left`, `trim_right`, `trim_left_matches`, and `trim_right_matches`, which will be deprecated in 1.33.0: * [`str::trim_end_matches`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_end_matches) * [`str::trim_end`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_end) * [`str::trim_start_matches`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_start_matches) * [`str::trim_start`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim_start) [§](https://doc.rust-lang.org/stable/releases.html#cargo-60) Cargo ------------------------------------------------------------------ * [`cargo run` doesn’t require specifying a package in workspaces.](https://github.com/rust-lang/cargo/pull/5877/) * [`cargo doc` now supports `--message-format=json`.](https://github.com/rust-lang/cargo/pull/5878/) This is equivalent to calling `rustdoc --error-format=json`. * [Cargo will now provide a progress bar for builds.](https://github.com/rust-lang/cargo/pull/5995/) [§](https://doc.rust-lang.org/stable/releases.html#misc-24) Misc ---------------------------------------------------------------- * [`rustdoc` allows you to specify what edition to treat your code as with the `--edition` option.](https://github.com/rust-lang/rust/pull/54057/) * [`rustdoc` now has the `--color` (specify whether to output color) and `--error-format` (specify error format, e.g. `json`) options.](https://github.com/rust-lang/rust/pull/53003/) * [We now distribute a `rust-gdbgui` script that invokes `gdbgui` with Rust debug symbols.](https://github.com/rust-lang/rust/pull/53774/) * [Attributes from Rust tools such as `rustfmt` or `clippy` are now available,](https://github.com/rust-lang/rust/pull/53459/) e.g. `#[rustfmt::skip]` will skip formatting the next item. [§](https://doc.rust-lang.org/stable/releases.html#version-1292-2018-10-11) Version 1.29.2 (2018-10-11) ======================================================================================================= * [Workaround for an aliasing-related LLVM bug, which caused miscompilation.](https://github.com/rust-lang/rust/pull/54639) * The `rls-preview` component on the windows-gnu targets has been restored. [§](https://doc.rust-lang.org/stable/releases.html#version-1291-2018-09-25) Version 1.29.1 (2018-09-25) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#security-notes) Security Notes --------------------------------------------------------------------------------- * The standard library’s `str::repeat` function contained an out of bounds write caused by an integer overflow. This has been fixed by deterministically panicking when an overflow happens. Thank you to Scott McMurray for responsibly disclosing this vulnerability to us. [§](https://doc.rust-lang.org/stable/releases.html#version-1290-2018-09-13) Version 1.29.0 (2018-09-13) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#compiler-62) Compiler ------------------------------------------------------------------------ * [Bumped minimum LLVM version to 5.0.](https://github.com/rust-lang/rust/pull/51899/) * [Added `powerpc64le-unknown-linux-musl` target.](https://github.com/rust-lang/rust/pull/51619/) * [Added `aarch64-unknown-hermit` and `x86_64-unknown-hermit` targets.](https://github.com/rust-lang/rust/pull/52861/) * [Upgraded to LLVM 7.](https://github.com/rust-lang/rust/pull/51966/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-63) Libraries -------------------------------------------------------------------------- * [`Once::call_once` no longer requires `Once` to be `'static`.](https://github.com/rust-lang/rust/pull/52239/) * [`BuildHasherDefault` now implements `PartialEq` and `Eq`.](https://github.com/rust-lang/rust/pull/52402/) * [`Box`, `Box`, and `Box` now implement `Clone`.](https://github.com/rust-lang/rust/pull/51912/) * [Implemented `PartialEq<&str>` for `OsString` and `PartialEq` for `&str`.](https://github.com/rust-lang/rust/pull/51178/) * [`Cell` now allows `T` to be unsized.](https://github.com/rust-lang/rust/pull/50494/) * [`SocketAddr` is now stable on Redox.](https://github.com/rust-lang/rust/pull/52656/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-58) Stabilized APIs -------------------------------------------------------------------------------------- * [`Arc::downcast`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.downcast) * [`Iterator::flatten`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flatten) * [`Rc::downcast`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.downcast) [§](https://doc.rust-lang.org/stable/releases.html#cargo-61) Cargo ------------------------------------------------------------------ * [Cargo can silently fix some bad lockfiles.](https://github.com/rust-lang/cargo/pull/5831/) You can use `--locked` to disable this behavior. * [`cargo-install` will now allow you to cross compile an install using `--target`.](https://github.com/rust-lang/cargo/pull/5614/) * [Added the `cargo-fix` subcommand to automatically move project code from 2015 edition to 2018.](https://github.com/rust-lang/cargo/pull/5723/) * [`cargo doc` can now optionally document private types using the `--document-private-items` flag.](https://github.com/rust-lang/cargo/pull/5543) [§](https://doc.rust-lang.org/stable/releases.html#misc-25) Misc ---------------------------------------------------------------- * [`rustdoc` now has the `--cap-lints` option which demotes all lints above the specified level to that level.](https://github.com/rust-lang/rust/pull/52354/) For example `--cap-lints warn` will demote `deny` and `forbid` lints to `warn`. * [`rustc` and `rustdoc` will now have the exit code of `1` if compilation fails and `101` if there is a panic.](https://github.com/rust-lang/rust/pull/52197/) * [A preview of clippy has been made available through rustup.](https://github.com/rust-lang/rust/pull/51122) You can install the preview with `rustup component add clippy-preview`. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-59) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`str::{slice_unchecked, slice_unchecked_mut}` are now deprecated.](https://github.com/rust-lang/rust/pull/51807/) Use `str::get_unchecked(begin..end)` instead. * [`std::env::home_dir` is now deprecated for its unintuitive behavior.](https://github.com/rust-lang/rust/pull/51656/) Consider using the `home_dir` function from https://crates.io/crates/dirs instead. * [`rustc` will no longer silently ignore invalid data in target spec.](https://github.com/rust-lang/rust/pull/52330/) * [`cfg` attributes and `--cfg` command line flags are now more strictly validated.](https://github.com/rust-lang/rust/pull/53893/) [§](https://doc.rust-lang.org/stable/releases.html#version-1280-2018-08-02) Version 1.28.0 (2018-08-02) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-63) Language ------------------------------------------------------------------------ * [The `#[repr(transparent)]` attribute is now stable.](https://github.com/rust-lang/rust/pull/51562/) This attribute allows a Rust newtype wrapper (`struct NewType(T);`) to be represented as the inner type across Foreign Function Interface (FFI) boundaries. * [The keywords `pure`, `sizeof`, `alignof`, and `offsetof` have been unreserved and can now be used as identifiers.](https://github.com/rust-lang/rust/pull/51196/) * [The `GlobalAlloc` trait and `#[global_allocator]` attribute are now stable.](https://github.com/rust-lang/rust/pull/51241/) This will allow users to specify a global allocator for their program. * [Unit test functions marked with the `#[test]` attribute can now return `Result<(), E: Debug>` in addition to `()`.](https://github.com/rust-lang/rust/pull/51298/) * [The `lifetime` specifier for `macro_rules!` is now stable.](https://github.com/rust-lang/rust/pull/50385/) This allows macros to easily target lifetimes. [§](https://doc.rust-lang.org/stable/releases.html#compiler-63) Compiler ------------------------------------------------------------------------ * [The `s` and `z` optimisation levels are now stable.](https://github.com/rust-lang/rust/pull/50265/) These optimisations prioritise making smaller binary sizes. `z` is the same as `s` with the exception that it does not vectorise loops, which typically results in an even smaller binary. * [The short error format is now stable.](https://github.com/rust-lang/rust/pull/49546/) Specified with `--error-format=short` this option will provide a more compressed output of rust error messages. * [Added a lint warning when you have duplicated `macro_export`s.](https://github.com/rust-lang/rust/pull/50143/) * [Reduced the number of allocations in the macro parser.](https://github.com/rust-lang/rust/pull/50855/) This can improve compile times of macro heavy crates on average by 5%. [§](https://doc.rust-lang.org/stable/releases.html#libraries-64) Libraries -------------------------------------------------------------------------- * [Implemented `Default` for `&mut str`.](https://github.com/rust-lang/rust/pull/51306/) * [Implemented `From` for all integer and unsigned number types.](https://github.com/rust-lang/rust/pull/50554/) * [Implemented `Extend` for `()`.](https://github.com/rust-lang/rust/pull/50234/) * [The `Debug` implementation of `time::Duration` should now be more easily human readable.](https://github.com/rust-lang/rust/pull/50364/) Previously a `Duration` of one second would printed as `Duration { secs: 1, nanos: 0 }` and will now be printed as `1s`. * [Implemented `From<&String>` for `Cow`, `From<&Vec>` for `Cow<[T]>`, `From>` for `CString`, `From, From, From<&CString>` for `Cow`, `From, From, From<&OsString>` for `Cow`, `From<&PathBuf>` for `Cow`, and `From>` for `PathBuf`.](https://github.com/rust-lang/rust/pull/50170/) * [Implemented `Shl` and `Shr` for `Wrapping` and `Wrapping`.](https://github.com/rust-lang/rust/pull/50465/) * [`DirEntry::metadata` now uses `fstatat` instead of `lstat` when possible.](https://github.com/rust-lang/rust/pull/51050/) This can provide up to a 40% speed increase. * [Improved error messages when using `format!`.](https://github.com/rust-lang/rust/pull/50610/) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-59) Stabilized APIs -------------------------------------------------------------------------------------- * [`Iterator::step_by`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.step_by) * [`Path::ancestors`](https://doc.rust-lang.org/std/path/struct.Path.html#method.ancestors) * [`SystemTime::UNIX_EPOCH`](https://doc.rust-lang.org/std/time/struct.SystemTime.html#associatedconstant.UNIX_EPOCH) * [`alloc::GlobalAlloc`](https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html) * [`alloc::Layout`](https://doc.rust-lang.org/std/alloc/struct.Layout.html) * [`alloc::LayoutErr`](https://doc.rust-lang.org/std/alloc/struct.LayoutErr.html) * [`alloc::System`](https://doc.rust-lang.org/std/alloc/struct.System.html) * [`alloc::alloc`](https://doc.rust-lang.org/std/alloc/fn.alloc.html) * [`alloc::alloc_zeroed`](https://doc.rust-lang.org/std/alloc/fn.alloc_zeroed.html) * [`alloc::dealloc`](https://doc.rust-lang.org/std/alloc/fn.dealloc.html) * [`alloc::realloc`](https://doc.rust-lang.org/std/alloc/fn.realloc.html) * [`alloc::handle_alloc_error`](https://doc.rust-lang.org/std/alloc/fn.handle_alloc_error.html) * [`btree_map::Entry::or_default`](https://doc.rust-lang.org/std/collections/btree_map/enum.Entry.html#method.or_default) * [`fmt::Alignment`](https://doc.rust-lang.org/std/fmt/enum.Alignment.html) * [`hash_map::Entry::or_default`](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.or_default) * [`iter::repeat_with`](https://doc.rust-lang.org/std/iter/fn.repeat_with.html) * [`num::NonZeroUsize`](https://doc.rust-lang.org/std/num/struct.NonZeroUsize.html) * [`num::NonZeroU128`](https://doc.rust-lang.org/std/num/struct.NonZeroU128.html) * [`num::NonZeroU16`](https://doc.rust-lang.org/std/num/struct.NonZeroU16.html) * [`num::NonZeroU32`](https://doc.rust-lang.org/std/num/struct.NonZeroU32.html) * [`num::NonZeroU64`](https://doc.rust-lang.org/std/num/struct.NonZeroU64.html) * [`num::NonZeroU8`](https://doc.rust-lang.org/std/num/struct.NonZeroU8.html) * [`ops::RangeBounds`](https://doc.rust-lang.org/std/ops/trait.RangeBounds.html) * [`slice::SliceIndex`](https://doc.rust-lang.org/std/slice/trait.SliceIndex.html) * [`slice::from_mut`](https://doc.rust-lang.org/std/slice/fn.from_mut.html) * [`slice::from_ref`](https://doc.rust-lang.org/stable/std/slice/fn.from_ref.html) * [`{Any + Send + Sync}::downcast_mut`](https://doc.rust-lang.org/std/any/trait.Any.html#method.downcast_mut-2) * [`{Any + Send + Sync}::downcast_ref`](https://doc.rust-lang.org/std/any/trait.Any.html#method.downcast_ref-2) * [`{Any + Send + Sync}::is`](https://doc.rust-lang.org/std/any/trait.Any.html#method.is-2) [§](https://doc.rust-lang.org/stable/releases.html#cargo-62) Cargo ------------------------------------------------------------------ * [Cargo will now no longer allow you to publish crates with build scripts that modify the `src` directory.](https://github.com/rust-lang/cargo/pull/5584/) The `src` directory in a crate should be considered to be immutable. [§](https://doc.rust-lang.org/stable/releases.html#misc-26) Misc ---------------------------------------------------------------- * [The `suggestion_applicability` field in `rustc`’s json output is now stable.](https://github.com/rust-lang/rust/pull/50486/) This will allow dev tools to check whether a code suggestion would apply to them. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-60) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Rust will consider trait objects with duplicated constraints to be the same type as without the duplicated constraint.](https://github.com/rust-lang/rust/pull/51276/) For example the below code will now fail to compile. trait Trait {} impl Trait + Send { fn test(&self) { println!("one"); } //~ ERROR duplicate definitions with name `test` } impl Trait + Send + Send { fn test(&self) { println!("two"); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Trait+%7B%7D%0A++++%0A++++impl+Trait+%2B+Send+%7B%0A++++++++fn+test(%26self)+%7B+println!(%22one%22);+%7D+//~+ERROR+duplicate+definitions+with+name+%60test%60%0A++++%7D%0A++++%0A++++impl+Trait+%2B+Send+%2B+Send+%7B%0A++++++++fn+test(%26self)+%7B+println!(%22two%22);+%7D%0A++++%7D%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#version-1272-2018-07-20) Version 1.27.2 (2018-07-20) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-61) Compatibility Notes ---------------------------------------------------------------------------------------------- * The borrow checker was fixed to avoid potential unsoundness when using match ergonomics: [#52213](https://github.com/rust-lang/rust/issues/52213) . [§](https://doc.rust-lang.org/stable/releases.html#version-1271-2018-07-10) Version 1.27.1 (2018-07-10) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#security-notes-1) Security Notes ----------------------------------------------------------------------------------- * rustdoc would execute plugins in the /tmp/rustdoc/plugins directory when running, which enabled executing code as some other user on a given machine. This release fixes that vulnerability; you can read more about this on the [blog](https://blog.rust-lang.org/2018/07/06/security-advisory-for-rustdoc.html) . The associated CVE is [CVE-2018-1000622](https://cve.mitre.org/cgi-bin/cvename.cgi?name=%20CVE-2018-1000622) . Thank you to Red Hat for responsibly disclosing this vulnerability to us. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-62) Compatibility Notes ---------------------------------------------------------------------------------------------- * The borrow checker was fixed to avoid an additional potential unsoundness when using match ergonomics: [#51415](https://github.com/rust-lang/rust/issues/51415) , [#49534](https://github.com/rust-lang/rust/issues/49534) . [§](https://doc.rust-lang.org/stable/releases.html#version-1270-2018-06-21) Version 1.27.0 (2018-06-21) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-64) Language ------------------------------------------------------------------------ * [Removed ‘proc’ from the reserved keywords list.](https://github.com/rust-lang/rust/pull/49699/) This allows `proc` to be used as an identifier. * [The dyn syntax is now available.](https://github.com/rust-lang/rust/pull/49968/) This syntax is equivalent to the bare `Trait` syntax, and should make it clearer when being used in tandem with `impl Trait` because it is equivalent to the following syntax: `&Trait == &dyn Trait`, `&mut Trait == &mut dyn Trait`, and `Box == Box`. * [Attributes on generic parameters such as types and lifetimes are now stable.](https://github.com/rust-lang/rust/pull/48851/) e.g. `fn foo<#[lifetime_attr] 'a, #[type_attr] T: 'a>() {}` * [The `#[must_use]` attribute can now also be used on functions as well as types.](https://github.com/rust-lang/rust/pull/48925/) It provides a lint that by default warns users when the value returned by a function has not been used. [§](https://doc.rust-lang.org/stable/releases.html#compiler-64) Compiler ------------------------------------------------------------------------ * [Added the `armv5te-unknown-linux-musleabi` target.](https://github.com/rust-lang/rust/pull/50423/) [§](https://doc.rust-lang.org/stable/releases.html#libraries-65) Libraries -------------------------------------------------------------------------- * [SIMD (Single Instruction Multiple Data) on x86/x86\_64 is now stable.](https://github.com/rust-lang/rust/pull/49664/) This includes [`arch::x86`](https://doc.rust-lang.org/std/arch/x86/index.html) & [`arch::x86_64`](https://doc.rust-lang.org/std/arch/x86_64/index.html) modules which contain SIMD intrinsics, a new macro called `is_x86_feature_detected!`, the `#[target_feature(enable="")]` attribute, and adding `target_feature = ""` to the `cfg` attribute. * [A lot of methods for `[u8]`, `f32`, and `f64` previously only available in std are now available in core.](https://github.com/rust-lang/rust/pull/49896/) * [The generic `Rhs` type parameter on `ops::{Shl, ShlAssign, Shr}` now defaults to `Self`.](https://github.com/rust-lang/rust/pull/49630/) * [`std::str::replace` now has the `#[must_use]` attribute](https://github.com/rust-lang/rust/pull/50177/) to clarify that the operation isn’t done in place. * [`Clone::clone`, `Iterator::collect`, and `ToOwned::to_owned` now have the `#[must_use]` attribute](https://github.com/rust-lang/rust/pull/49533/) to warn about unused potentially expensive allocations. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-60) Stabilized APIs -------------------------------------------------------------------------------------- * [`DoubleEndedIterator::rfind`](https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.rfind) * [`DoubleEndedIterator::rfold`](https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.rfold) * [`DoubleEndedIterator::try_rfold`](https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.try_rfold) * [`Duration::from_micros`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_micros) * [`Duration::from_nanos`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.from_nanos) * [`Duration::subsec_micros`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_micros) * [`Duration::subsec_millis`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.subsec_millis) * [`HashMap::remove_entry`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.remove_entry) * [`Iterator::try_fold`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.try_fold) * [`Iterator::try_for_each`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.try_for_each) * [`NonNull::cast`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.cast) * [`Option::filter`](https://doc.rust-lang.org/std/option/enum.Option.html#method.filter) * [`String::replace_range`](https://doc.rust-lang.org/std/string/struct.String.html#method.replace_range) * [`Take::set_limit`](https://doc.rust-lang.org/std/io/struct.Take.html#method.set_limit) * [`hint::unreachable_unchecked`](https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked.html) * [`os::unix::process::parent_id`](https://doc.rust-lang.org/std/os/unix/process/fn.parent_id.html) * [`ptr::swap_nonoverlapping`](https://doc.rust-lang.org/std/ptr/fn.swap_nonoverlapping.html) * [`slice::rsplit_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit_mut) * [`slice::rsplit`](https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit) * [`slice::swap_with_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.swap_with_slice) [§](https://doc.rust-lang.org/stable/releases.html#cargo-63) Cargo ------------------------------------------------------------------ * [`cargo-metadata` now includes `authors`, `categories`, `keywords`, `readme`, and `repository` fields.](https://github.com/rust-lang/cargo/pull/5386/) * [`cargo-metadata` now includes a package’s `metadata` table.](https://github.com/rust-lang/cargo/pull/5360/) * [Added the `--target-dir` optional argument.](https://github.com/rust-lang/cargo/pull/5393/) This allows you to specify a different directory than `target` for placing compilation artifacts. * [Cargo will be adding automatic target inference for binaries, benchmarks, examples, and tests in the Rust 2018 edition.](https://github.com/rust-lang/cargo/pull/5335/) If your project specifies specific targets, e.g. using `[[bin]]`, and have other binaries in locations where cargo would infer a binary, Cargo will produce a warning. You can disable this feature ahead of time by setting any of the following to false: `autobins`, `autobenches`, `autoexamples`, `autotests`. * [Cargo will now cache compiler information.](https://github.com/rust-lang/cargo/pull/5359/) This can be disabled by setting `CARGO_CACHE_RUSTC_INFO=0` in your environment. [§](https://doc.rust-lang.org/stable/releases.html#misc-27) Misc ---------------------------------------------------------------- * [Added “The Rustc book” into the official documentation.](https://github.com/rust-lang/rust/pull/49707/) [“The Rustc book”](https://doc.rust-lang.org/rustc) documents and teaches how to use the rustc compiler. * [All books available on `doc.rust-lang.org` are now searchable.](https://github.com/rust-lang/rust/pull/49623/) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-63) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Calling a `CharExt` or `StrExt` method directly on core will no longer work.](https://github.com/rust-lang/rust/pull/49896/) e.g. `::core::prelude::v1::StrExt::is_empty("")` will not compile, `"".is_empty()` will still compile. * [`Debug` output on `atomic::{AtomicBool, AtomicIsize, AtomicPtr, AtomicUsize}` will only print the inner type.](https://github.com/rust-lang/rust/pull/48553/) E.g. `print!("{:?}", AtomicBool::new(true))` will print `true`, not `AtomicBool(true)`. * [The maximum number for `repr(align(N))` is now 2²⁹.](https://github.com/rust-lang/rust/pull/50378/) Previously you could enter higher numbers but they were not supported by LLVM. Up to 512MB alignment should cover all use cases. * The `.description()` method on the `std::error::Error` trait [has been soft-deprecated](https://github.com/rust-lang/rust/pull/50163) . It is no longer required to implement it. [§](https://doc.rust-lang.org/stable/releases.html#version-1262-2018-06-05) Version 1.26.2 (2018-06-05) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-64) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The borrow checker was fixed to avoid unsoundness when using match ergonomics.](https://github.com/rust-lang/rust/issues/51117) [§](https://doc.rust-lang.org/stable/releases.html#version-1261-2018-05-29) Version 1.26.1 (2018-05-29) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#tools) Tools --------------------------------------------------------------- * [RLS now works on Windows.](https://github.com/rust-lang/rust/issues/50646) * [Rustfmt stopped badly formatting text in some cases.](https://github.com/rust-lang-nursery/rustfmt/issues/2695) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-65) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`fn main() -> impl Trait` no longer works for non-Termination trait.](https://github.com/rust-lang/rust/pull/50656) This reverts an accidental stabilization. * [`NaN > NaN` no longer returns true in const-fn contexts.](https://github.com/rust-lang/rust/pull/50812) * [Prohibit using turbofish for `impl Trait` in method arguments.](https://github.com/rust-lang/rust/issues/50950) [§](https://doc.rust-lang.org/stable/releases.html#version-1260-2018-05-10) Version 1.26.0 (2018-05-10) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-65) Language ------------------------------------------------------------------------ * [Closures now implement `Copy` and/or `Clone` if all captured variables implement either or both traits.](https://github.com/rust-lang/rust/pull/49299) * [The inclusive range syntax e.g. `for x in 0..=10` is now stable.](https://github.com/rust-lang/rust/pull/47813) * [The `'_` lifetime is now stable. The underscore lifetime can be used anywhere a lifetime can be elided.](https://github.com/rust-lang/rust/pull/49458) * [`impl Trait` is now stable allowing you to have abstract types in returns or in function parameters.](https://github.com/rust-lang/rust/pull/49255) E.g. `fn foo() -> impl Iterator` or `fn open(path: impl AsRef)`. * [Pattern matching will now automatically apply dereferences.](https://github.com/rust-lang/rust/pull/49394) * [128-bit integers in the form of `u128` and `i128` are now stable.](https://github.com/rust-lang/rust/pull/49101) * [`main` can now return `Result<(), E: Debug>`](https://github.com/rust-lang/rust/pull/49162) in addition to `()`. * [A lot of operations are now available in a const context.](https://github.com/rust-lang/rust/pull/46882) E.g. You can now index into constant arrays, reference and dereference into constants, and use tuple struct constructors. * [Fixed entry slice patterns are now stable.](https://github.com/rust-lang/rust/pull/48516) E.g. let points = [1, 2, 3, 4]; match points { [1, 2, 3, 4] => println!("All points were sequential."), _ => println!("Not all points were sequential."), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+points+=+%5B1,+2,+3,+4%5D;%0A++++match+points+%7B%0A++++++++%5B1,+2,+3,+4%5D+=%3E+println!(%22All+points+were+sequential.%22),%0A++++++++_+=%3E+println!(%22Not+all+points+were+sequential.%22),%0A++++%7D%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-65) Compiler ------------------------------------------------------------------------ * [LLD is now used as the default linker for `wasm32-unknown-unknown`.](https://github.com/rust-lang/rust/pull/48125) * [Fixed exponential projection complexity on nested types.](https://github.com/rust-lang/rust/pull/48296) This can provide up to a ~12% reduction in compile times for certain crates. * [Added the `--remap-path-prefix` option to rustc.](https://github.com/rust-lang/rust/pull/48359) Allowing you to remap path prefixes outputted by the compiler. * [Added `powerpc-unknown-netbsd` target.](https://github.com/rust-lang/rust/pull/48281) [§](https://doc.rust-lang.org/stable/releases.html#libraries-66) Libraries -------------------------------------------------------------------------- * [Implemented `From for usize` & `From<{u8, i16}> for isize`.](https://github.com/rust-lang/rust/pull/49305) * [Added hexadecimal formatting for integers with fmt::Debug](https://github.com/rust-lang/rust/pull/48978) e.g. `assert!(format!("{:02x?}", b"Foo\0") == "[46, 6f, 6f, 00]")` * [Implemented `Default, Hash` for `cmp::Reverse`.](https://github.com/rust-lang/rust/pull/48628) * [Optimized `str::repeat` being 8x faster in large cases.](https://github.com/rust-lang/rust/pull/48657) * [`ascii::escape_default` is now available in libcore.](https://github.com/rust-lang/rust/pull/48735) * [Trailing commas are now supported in std and core macros.](https://github.com/rust-lang/rust/pull/48056) * [Implemented `Copy, Clone` for `cmp::Reverse`](https://github.com/rust-lang/rust/pull/47379) * [Implemented `Clone` for `char::{ToLowercase, ToUppercase}`.](https://github.com/rust-lang/rust/pull/48629) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-61) Stabilized APIs -------------------------------------------------------------------------------------- * [`*const T::add`](https://doc.rust-lang.org/std/primitive.pointer.html#method.add) * [`*const T::copy_to_nonoverlapping`](https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to_nonoverlapping) * [`*const T::copy_to`](https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to) * [`*const T::read_unaligned`](https://doc.rust-lang.org/std/primitive.pointer.html#method.read_unaligned) * [`*const T::read_volatile`](https://doc.rust-lang.org/std/primitive.pointer.html#method.read_volatile) * [`*const T::read`](https://doc.rust-lang.org/std/primitive.pointer.html#method.read) * [`*const T::sub`](https://doc.rust-lang.org/std/primitive.pointer.html#method.sub) * [`*const T::wrapping_add`](https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_add) * [`*const T::wrapping_sub`](https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_sub) * [`*mut T::add`](https://doc.rust-lang.org/std/primitive.pointer.html#method.add-1) * [`*mut T::copy_to_nonoverlapping`](https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to_nonoverlapping-1) * [`*mut T::copy_to`](https://doc.rust-lang.org/std/primitive.pointer.html#method.copy_to-1) * [`*mut T::read_unaligned`](https://doc.rust-lang.org/std/primitive.pointer.html#method.read_unaligned-1) * [`*mut T::read_volatile`](https://doc.rust-lang.org/std/primitive.pointer.html#method.read_volatile-1) * [`*mut T::read`](https://doc.rust-lang.org/std/primitive.pointer.html#method.read-1) * [`*mut T::replace`](https://doc.rust-lang.org/std/primitive.pointer.html#method.replace) * [`*mut T::sub`](https://doc.rust-lang.org/std/primitive.pointer.html#method.sub-1) * [`*mut T::swap`](https://doc.rust-lang.org/std/primitive.pointer.html#method.swap) * [`*mut T::wrapping_add`](https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_add-1) * [`*mut T::wrapping_sub`](https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_sub-1) * [`*mut T::write_bytes`](https://doc.rust-lang.org/std/primitive.pointer.html#method.write_bytes) * [`*mut T::write_unaligned`](https://doc.rust-lang.org/std/primitive.pointer.html#method.write_unaligned) * [`*mut T::write_volatile`](https://doc.rust-lang.org/std/primitive.pointer.html#method.write_volatile) * [`*mut T::write`](https://doc.rust-lang.org/std/primitive.pointer.html#method.write) * [`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak) * [`FromUtf8Error::as_bytes`](https://doc.rust-lang.org/std/string/struct.FromUtf8Error.html#method.as_bytes) * [`LocalKey::try_with`](https://doc.rust-lang.org/std/thread/struct.LocalKey.html#method.try_with) * [`Option::cloned`](https://doc.rust-lang.org/std/option/enum.Option.html#method.cloned) * [`btree_map::Entry::and_modify`](https://doc.rust-lang.org/std/collections/btree_map/enum.Entry.html#method.and_modify) * [`fs::read_to_string`](https://doc.rust-lang.org/std/fs/fn.read_to_string.html) * [`fs::read`](https://doc.rust-lang.org/std/fs/fn.read.html) * [`fs::write`](https://doc.rust-lang.org/std/fs/fn.write.html) * [`hash_map::Entry::and_modify`](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.and_modify) * [`iter::FusedIterator`](https://doc.rust-lang.org/std/iter/trait.FusedIterator.html) * [`ops::RangeInclusive`](https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html) * [`ops::RangeToInclusive`](https://doc.rust-lang.org/std/ops/struct.RangeToInclusive.html) * [`process::id`](https://doc.rust-lang.org/std/process/fn.id.html) * [`slice::rotate_left`](https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_left) * [`slice::rotate_right`](https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_right) * [`String::retain`](https://doc.rust-lang.org/std/string/struct.String.html#method.retain) [§](https://doc.rust-lang.org/stable/releases.html#cargo-64) Cargo ------------------------------------------------------------------ * [Cargo will now output path to custom commands when `-v` is passed with `--list`](https://github.com/rust-lang/cargo/pull/5041) * [The Cargo binary version is now the same as the Rust version](https://github.com/rust-lang/cargo/pull/5083) [§](https://doc.rust-lang.org/stable/releases.html#misc-28) Misc ---------------------------------------------------------------- * [The second edition of “The Rust Programming Language” book is now recommended over the first.](https://github.com/rust-lang/rust/pull/48404) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-66) Compatibility Notes ---------------------------------------------------------------------------------------------- * [aliasing a `Fn` trait as `dyn` no longer works.](https://github.com/rust-lang/rust/pull/48481) E.g. the following syntax is now invalid. use std::ops::Fn as dyn; fn g(_: Box) {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::ops::Fn+as+dyn;%0A++++fn+g(_:+Box%3Cdyn(std::fmt::Debug)%3E)+%7B%7D%0A%7D&edition=2015 "Run code") * [The result of dereferences are no longer promoted to `'static`.](https://github.com/rust-lang/rust/pull/47408) e.g. fn main() { const PAIR: &(i32, i32) = &(0, 1); let _reversed_pair: &'static _ = &(PAIR.1, PAIR.0); // Doesn't work } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++const+PAIR:+%26(i32,+i32)+=+%26(0,+1);%0A++++let+_reversed_pair:+%26%27static+_+=+%26(PAIR.1,+PAIR.0);+//+Doesn%27t+work%0A%7D&edition=2015 "Run code") * [Deprecate `AsciiExt` trait in favor of inherent methods.](https://github.com/rust-lang/rust/pull/49109) * [`".e0"` will now no longer parse as `0.0` and will instead cause an error.](https://github.com/rust-lang/rust/pull/48235) * [Removed hoedown from rustdoc.](https://github.com/rust-lang/rust/pull/48274) * [Bounds on higher-kinded lifetimes a hard error.](https://github.com/rust-lang/rust/pull/48326) [§](https://doc.rust-lang.org/stable/releases.html#version-1250-2018-03-29) Version 1.25.0 (2018-03-29) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-66) Language ------------------------------------------------------------------------ * [The `#[repr(align(x))]` attribute is now stable.](https://github.com/rust-lang/rust/pull/47006) [RFC 1358](https://github.com/rust-lang/rfcs/pull/1358) * [You can now use nested groups of imports.](https://github.com/rust-lang/rust/pull/47948) e.g. `use std::{fs::File, io::Read, path::{Path, PathBuf}};` * [You can now have `|` at the start of a match arm.](https://github.com/rust-lang/rust/pull/47947) e.g. enum Foo { A, B, C } fn main() { let x = Foo::A; match x { | Foo::A | Foo::B => println!("AB"), | Foo::C => println!("C"), } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Aenum+Foo+%7B+A,+B,+C+%7D%0A%0Afn+main()+%7B%0A++++let+x+=+Foo::A;%0A++++match+x+%7B%0A++++++++%7C+Foo::A%0A++++++++%7C+Foo::B+=%3E+println!(%22AB%22),%0A++++++++%7C+Foo::C+=%3E+println!(%22C%22),%0A++++%7D%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-66) Compiler ------------------------------------------------------------------------ * [Upgraded to LLVM 6.](https://github.com/rust-lang/rust/pull/47828) * [Added `-C lto=val` option.](https://github.com/rust-lang/rust/pull/47521) * [Added `i586-unknown-linux-musl` target](https://github.com/rust-lang/rust/pull/47282) [§](https://doc.rust-lang.org/stable/releases.html#libraries-67) Libraries -------------------------------------------------------------------------- * [Impl Send for `process::Command` on Unix.](https://github.com/rust-lang/rust/pull/47760) * [Impl PartialEq and Eq for `ParseCharError`.](https://github.com/rust-lang/rust/pull/47790) * [`UnsafeCell::into_inner` is now safe.](https://github.com/rust-lang/rust/pull/47204) * [Implement libstd for CloudABI.](https://github.com/rust-lang/rust/pull/47268) * [`Float::{from_bits, to_bits}` is now available in libcore.](https://github.com/rust-lang/rust/pull/46931) * [Implement `AsRef` for Component](https://github.com/rust-lang/rust/pull/46985) * [Implemented `Write` for `Cursor<&mut Vec>`](https://github.com/rust-lang/rust/pull/46830) * [Moved `Duration` to libcore.](https://github.com/rust-lang/rust/pull/46666) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-62) Stabilized APIs -------------------------------------------------------------------------------------- * [`Location::column`](https://doc.rust-lang.org/std/panic/struct.Location.html#method.column) * [`ptr::NonNull`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html) The following functions can now be used in a constant expression. eg. `static MINUTE: Duration = Duration::from_secs(60);` * [`Duration::new`](https://github.com/rust-lang/rust/pull/47300) * [`Duration::from_secs`](https://github.com/rust-lang/rust/pull/47300) * [`Duration::from_millis`](https://github.com/rust-lang/rust/pull/47300) [§](https://doc.rust-lang.org/stable/releases.html#cargo-65) Cargo ------------------------------------------------------------------ * [`cargo new` no longer removes `rust` or `rs` prefixes/suffixes.](https://github.com/rust-lang/cargo/pull/5013) * [`cargo new` now defaults to creating a binary crate, instead of a library crate.](https://github.com/rust-lang/cargo/pull/5029) [§](https://doc.rust-lang.org/stable/releases.html#misc-29) Misc ---------------------------------------------------------------- * [Rust by example is now shipped with new releases](https://github.com/rust-lang/rust/pull/46196) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-67) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Deprecated `net::lookup_host`.](https://github.com/rust-lang/rust/pull/47510) * [`rustdoc` has switched to pulldown as the default markdown renderer.](https://github.com/rust-lang/rust/pull/47398) * The borrow checker was sometimes incorrectly permitting overlapping borrows around indexing operations (see [#47349](https://github.com/rust-lang/rust/pull/47349) ). This has been fixed (which also enabled some correct code that used to cause errors (e.g. [#33903](https://github.com/rust-lang/rust/pull/33903) and [#46095](https://github.com/rust-lang/rust/pull/46095) ). * [Removed deprecated unstable attribute `#[simd]`.](https://github.com/rust-lang/rust/pull/47251) [§](https://doc.rust-lang.org/stable/releases.html#version-1241-2018-03-01) Version 1.24.1 (2018-03-01) ======================================================================================================= * [Do not abort when unwinding through FFI](https://github.com/rust-lang/rust/issues/48251) * [Emit UTF-16 files for linker arguments on Windows](https://github.com/rust-lang/rust/issues/48318) * [Make the error index generator work again](https://github.com/rust-lang/rust/issues/48308) * [Cargo will warn on Windows 7 if an update is needed](https://github.com/rust-lang/cargo/pull/5069) . [§](https://doc.rust-lang.org/stable/releases.html#version-1240-2018-02-15) Version 1.24.0 (2018-02-15) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-67) Language ------------------------------------------------------------------------ * [External `sysv64` ffi is now available.](https://github.com/rust-lang/rust/pull/46528) eg. `extern "sysv64" fn foo () {}` [§](https://doc.rust-lang.org/stable/releases.html#compiler-67) Compiler ------------------------------------------------------------------------ * [rustc now uses 16 codegen units by default for release builds.](https://github.com/rust-lang/rust/pull/46910) For the fastest builds, utilize `codegen-units=1`. * [Added `armv4t-unknown-linux-gnueabi` target.](https://github.com/rust-lang/rust/pull/47018) * [Add `aarch64-unknown-openbsd` support](https://github.com/rust-lang/rust/pull/46760) [§](https://doc.rust-lang.org/stable/releases.html#libraries-68) Libraries -------------------------------------------------------------------------- * [`str::find::` now uses memchr.](https://github.com/rust-lang/rust/pull/46735) This should lead to a 10x improvement in performance in the majority of cases. * [`OsStr`’s `Debug` implementation is now lossless and consistent with Windows.](https://github.com/rust-lang/rust/pull/46798) * [`time::{SystemTime, Instant}` now implement `Hash`.](https://github.com/rust-lang/rust/pull/46828) * [impl `From` for `AtomicBool`](https://github.com/rust-lang/rust/pull/46293) * [impl `From<{CString, &CStr}>` for `{Arc, Rc}`](https://github.com/rust-lang/rust/pull/45990) * [impl `From<{OsString, &OsStr}>` for `{Arc, Rc}`](https://github.com/rust-lang/rust/pull/45990) * [impl `From<{PathBuf, &Path}>` for `{Arc, Rc}`](https://github.com/rust-lang/rust/pull/45990) * [float::from\_bits now just uses transmute.](https://github.com/rust-lang/rust/pull/46012) This provides some optimisations from LLVM. * [Copied `AsciiExt` methods onto `char`](https://github.com/rust-lang/rust/pull/46077) * [Remove `T: Sized` requirement on `ptr::is_null()`](https://github.com/rust-lang/rust/pull/46094) * [impl `From` for `{TryRecvError, RecvTimeoutError}`](https://github.com/rust-lang/rust/pull/45506) * [Optimised `f32::{min, max}` to generate more efficient x86 assembly](https://github.com/rust-lang/rust/pull/47080) * [`[u8]::contains` now uses memchr which provides a 3x speed improvement](https://github.com/rust-lang/rust/pull/46713) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-63) Stabilized APIs -------------------------------------------------------------------------------------- * [`RefCell::replace`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.replace) * [`RefCell::swap`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.swap) * [`atomic::spin_loop_hint`](https://doc.rust-lang.org/std/sync/atomic/fn.spin_loop_hint.html) The following functions can now be used in a constant expression. eg. `let buffer: [u8; size_of::()];`, `static COUNTER: AtomicUsize = AtomicUsize::new(1);` * [`AtomicBool::new`](https://github.com/rust-lang/rust/pull/46287) * [`AtomicUsize::new`](https://github.com/rust-lang/rust/pull/46287) * [`AtomicIsize::new`](https://github.com/rust-lang/rust/pull/46287) * [`AtomicPtr::new`](https://github.com/rust-lang/rust/pull/46287) * [`Cell::new`](https://github.com/rust-lang/rust/pull/46287) * [`{integer}::min_value`](https://github.com/rust-lang/rust/pull/46287) * [`{integer}::max_value`](https://github.com/rust-lang/rust/pull/46287) * [`mem::size_of`](https://github.com/rust-lang/rust/pull/46287) * [`mem::align_of`](https://github.com/rust-lang/rust/pull/46287) * [`ptr::null`](https://github.com/rust-lang/rust/pull/46287) * [`ptr::null_mut`](https://github.com/rust-lang/rust/pull/46287) * [`RefCell::new`](https://github.com/rust-lang/rust/pull/46287) * [`UnsafeCell::new`](https://github.com/rust-lang/rust/pull/46287) [§](https://doc.rust-lang.org/stable/releases.html#cargo-66) Cargo ------------------------------------------------------------------ * [Added a `workspace.default-members` config that overrides implied `--all` in virtual workspaces.](https://github.com/rust-lang/cargo/pull/4743) * [Enable incremental by default on development builds.](https://github.com/rust-lang/cargo/pull/4817) Also added configuration keys to `Cargo.toml` and `.cargo/config` to disable on a per-project or global basis respectively. [§](https://doc.rust-lang.org/stable/releases.html#misc-30) Misc ---------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-68) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Floating point types `Debug` impl now always prints a decimal point.](https://github.com/rust-lang/rust/pull/46831) * [`Ipv6Addr` now rejects superfluous `::`’s in IPv6 addresses](https://github.com/rust-lang/rust/pull/46671) This is in accordance with IETF RFC 4291 §2.2. * [Unwinding will no longer go past FFI boundaries, and will instead abort.](https://github.com/rust-lang/rust/pull/46833) * [`Formatter::flags` method is now deprecated.](https://github.com/rust-lang/rust/pull/46284) The `sign_plus`, `sign_minus`, `alternate`, and `sign_aware_zero_pad` should be used instead. * [Leading zeros in tuple struct members is now an error](https://github.com/rust-lang/rust/pull/47084) * [`column!()` macro is one-based instead of zero-based](https://github.com/rust-lang/rust/pull/46977) * [`fmt::Arguments` can no longer be shared across threads](https://github.com/rust-lang/rust/pull/45198) * [Access to `#[repr(packed)]` struct fields is now unsafe](https://github.com/rust-lang/rust/pull/44884) * [Cargo sets a different working directory for the compiler](https://github.com/rust-lang/cargo/pull/4788) [§](https://doc.rust-lang.org/stable/releases.html#version-1230-2018-01-04) Version 1.23.0 (2018-01-04) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-68) Language ------------------------------------------------------------------------ * [Arbitrary `auto` traits are now permitted in trait objects.](https://github.com/rust-lang/rust/pull/45772) * [rustc now uses subtyping on the left hand side of binary operations.](https://github.com/rust-lang/rust/pull/45435) Which should fix some confusing errors in some operations. [§](https://doc.rust-lang.org/stable/releases.html#compiler-68) Compiler ------------------------------------------------------------------------ * [Enabled `TrapUnreachable` in LLVM which should mitigate the impact of undefined behavior.](https://github.com/rust-lang/rust/pull/45920) * [rustc now suggests renaming import if names clash.](https://github.com/rust-lang/rust/pull/45660) * [Display errors/warnings correctly when there are zero-width or wide characters.](https://github.com/rust-lang/rust/pull/45711) * [rustc now avoids unnecessary copies of arguments that are simple bindings](https://github.com/rust-lang/rust/pull/45380) This should improve memory usage on average by 5-10%. * [Updated musl used to build musl rustc to 1.1.17](https://github.com/rust-lang/rust/pull/45393) [§](https://doc.rust-lang.org/stable/releases.html#libraries-69) Libraries -------------------------------------------------------------------------- * [Allow a trailing comma in `assert_eq/ne` macro](https://github.com/rust-lang/rust/pull/45887) * [Implement Hash for raw pointers to unsized types](https://github.com/rust-lang/rust/pull/45483) * [impl `From<*mut T>` for `AtomicPtr`](https://github.com/rust-lang/rust/pull/45610) * [impl `From` for `AtomicUsize/AtomicIsize`.](https://github.com/rust-lang/rust/pull/45610) * [Removed the `T: Sync` requirement for `RwLock: Send`](https://github.com/rust-lang/rust/pull/45267) * [Removed `T: Sized` requirement for `{<*const T>, <*mut T>}::as_ref` and `<*mut T>::as_mut`](https://github.com/rust-lang/rust/pull/44932) * [Optimized `Thread::{park, unpark}` implementation](https://github.com/rust-lang/rust/pull/45524) * [Improved `SliceExt::binary_search` performance.](https://github.com/rust-lang/rust/pull/45333) * [impl `FromIterator<()>` for `()`](https://github.com/rust-lang/rust/pull/45379) * [Copied `AsciiExt` trait methods to primitive types.](https://github.com/rust-lang/rust/pull/44042) Use of `AsciiExt` is now deprecated. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-64) Stabilized APIs -------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#cargo-67) Cargo ------------------------------------------------------------------ * [Cargo now supports uninstallation of multiple packages](https://github.com/rust-lang/cargo/pull/4561) eg. `cargo uninstall foo bar` uninstalls `foo` and `bar`. * [Added unit test checking to `cargo check`](https://github.com/rust-lang/cargo/pull/4592) * [Cargo now lets you install a specific version using `cargo install --version`](https://github.com/rust-lang/cargo/pull/4637) [§](https://doc.rust-lang.org/stable/releases.html#misc-31) Misc ---------------------------------------------------------------- * [Releases now ship with the Cargo book documentation.](https://github.com/rust-lang/rust/pull/45692) * [rustdoc now prints rendering warnings on every run.](https://github.com/rust-lang/rust/pull/45324) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-69) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Changes have been made to type equality to make it more correct, in rare cases this could break some code.](https://github.com/rust-lang/rust/pull/45853) [Tracking issue for further information](https://github.com/rust-lang/rust/issues/45852) * [`char::escape_debug` now uses Unicode 10 over 9.](https://github.com/rust-lang/rust/pull/45571) * [Upgraded Android SDK to 27, and NDK to r15c.](https://github.com/rust-lang/rust/pull/45580) This drops support for Android 9, the minimum supported version is Android 14. * [Bumped the minimum LLVM to 3.9](https://github.com/rust-lang/rust/pull/45326) [§](https://doc.rust-lang.org/stable/releases.html#version-1221-2017-11-22) Version 1.22.1 (2017-11-22) ======================================================================================================= * [Update Cargo to fix an issue with macOS 10.13 “High Sierra”](https://github.com/rust-lang/rust/pull/46183) [§](https://doc.rust-lang.org/stable/releases.html#version-1220-2017-11-22) Version 1.22.0 (2017-11-22) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-69) Language ------------------------------------------------------------------------ * [`non_snake_case` lint now allows extern no-mangle functions](https://github.com/rust-lang/rust/pull/44966) * [Now accepts underscores in unicode escapes](https://github.com/rust-lang/rust/pull/43716) * [`T op= &T` now works for numeric types.](https://github.com/rust-lang/rust/pull/44287) eg. `let mut x = 2; x += &8;` * [types that impl `Drop` are now allowed in `const` and `static` types](https://github.com/rust-lang/rust/pull/44456) [§](https://doc.rust-lang.org/stable/releases.html#compiler-69) Compiler ------------------------------------------------------------------------ * [rustc now defaults to having 16 codegen units at debug on supported platforms.](https://github.com/rust-lang/rust/pull/45064) * [rustc will no longer inline in codegen units when compiling for debug](https://github.com/rust-lang/rust/pull/45075) This should decrease compile times for debug builds. * [strict memory alignment now enabled on ARMv6](https://github.com/rust-lang/rust/pull/45094) * [Remove support for the PNaCl target `le32-unknown-nacl`](https://github.com/rust-lang/rust/pull/45041) [§](https://doc.rust-lang.org/stable/releases.html#libraries-70) Libraries -------------------------------------------------------------------------- * [Allow atomic operations up to 32 bits on `armv5te_unknown_linux_gnueabi`](https://github.com/rust-lang/rust/pull/44978) * [`Box` now impls `From>`](https://github.com/rust-lang/rust/pull/44466) * [`std::mem::Discriminant` is now guaranteed to be `Send + Sync`](https://github.com/rust-lang/rust/pull/45095) * [`fs::copy` now returns the length of the main stream on NTFS.](https://github.com/rust-lang/rust/pull/44895) * [Properly detect overflow in `Instant += Duration`.](https://github.com/rust-lang/rust/pull/44220) * [impl `Hasher` for `{&mut Hasher, Box}`](https://github.com/rust-lang/rust/pull/44015) * [impl `fmt::Debug` for `SplitWhitespace`.](https://github.com/rust-lang/rust/pull/44303) * [`Option` now impls `Try`](https://github.com/rust-lang/rust/pull/42526) This allows for using `?` with `Option` types. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-65) Stabilized APIs -------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/releases.html#cargo-68) Cargo ------------------------------------------------------------------ * [Cargo will now build multi file examples in subdirectories of the `examples` folder that have a `main.rs` file.](https://github.com/rust-lang/cargo/pull/4496) * [Changed `[root]` to `[package]` in `Cargo.lock`](https://github.com/rust-lang/cargo/pull/4571) Packages with the old format will continue to work and can be updated with `cargo update`. * [Now supports vendoring git repositories](https://github.com/rust-lang/cargo/pull/3992) [§](https://doc.rust-lang.org/stable/releases.html#misc-32) Misc ---------------------------------------------------------------- * [`libbacktrace` is now available on Apple platforms.](https://github.com/rust-lang/rust/pull/44251) * [Stabilised the `compile_fail` attribute for code fences in doc-comments.](https://github.com/rust-lang/rust/pull/43949) This now lets you specify that a given code example will fail to compile. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-70) Compatibility Notes ---------------------------------------------------------------------------------------------- * [The minimum Android version that rustc can build for has been bumped to `4.0` from `2.3`](https://github.com/rust-lang/rust/pull/45656) * [Allowing `T op= &T` for numeric types has broken some type inference cases](https://github.com/rust-lang/rust/issues/45480) [§](https://doc.rust-lang.org/stable/releases.html#version-1210-2017-10-12) Version 1.21.0 (2017-10-12) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-70) Language ------------------------------------------------------------------------ * [You can now use static references for literals.](https://github.com/rust-lang/rust/pull/43838) Example: fn main() { let x: &'static u32 = &0; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+x:+%26%27static+u32+=+%260;%0A%7D&edition=2015 "Run code") * [Relaxed path syntax. Optional `::` before `<` is now allowed in all contexts.](https://github.com/rust-lang/rust/pull/43540) Example: my_macro!(Vec::new); // Always worked my_macro!(Vec::::new); // Now works [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++my_macro!(Vec%3Ci32%3E::new);+//+Always+worked%0A++++my_macro!(Vec::%3Ci32%3E::new);%0A%7D&edition=2015 "Run code") [§](https://doc.rust-lang.org/stable/releases.html#compiler-70) Compiler ------------------------------------------------------------------------ * [Upgraded jemalloc to 4.5.0](https://github.com/rust-lang/rust/pull/43911) * [Enabled unwinding panics on Redox](https://github.com/rust-lang/rust/pull/43917) * [Now runs LLVM in parallel during translation phase.](https://github.com/rust-lang/rust/pull/43506) This should reduce peak memory usage. [§](https://doc.rust-lang.org/stable/releases.html#libraries-71) Libraries -------------------------------------------------------------------------- * [Generate builtin impls for `Clone` for all arrays and tuples that are `T: Clone`](https://github.com/rust-lang/rust/pull/43690) * [`Stdin`, `Stdout`, and `Stderr` now implement `AsRawFd`.](https://github.com/rust-lang/rust/pull/43459) * [`Rc` and `Arc` now implement `From<&[T]> where T: Clone`, `From`, `From`, `From> where T: ?Sized`, and `From>`.](https://github.com/rust-lang/rust/pull/42565) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-66) Stabilized APIs -------------------------------------------------------------------------------------- [`std::mem::discriminant`](https://doc.rust-lang.org/std/mem/fn.discriminant.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-69) Cargo ------------------------------------------------------------------ * [You can now call `cargo install` with multiple package names](https://github.com/rust-lang/cargo/pull/4216) * [Cargo commands inside a virtual workspace will now implicitly pass `--all`](https://github.com/rust-lang/cargo/pull/4335) * [Added a `[patch]` section to `Cargo.toml` to handle prepublication dependencies](https://github.com/rust-lang/cargo/pull/4123) [RFC 1969](https://github.com/rust-lang/rfcs/pull/1969) * [`include` & `exclude` fields in `Cargo.toml` now accept gitignore like patterns](https://github.com/rust-lang/cargo/pull/4270) * [Added the `--all-targets` option](https://github.com/rust-lang/cargo/pull/4400) * [Using required dependencies as a feature is now deprecated and emits a warning](https://github.com/rust-lang/cargo/pull/4364) [§](https://doc.rust-lang.org/stable/releases.html#misc-33) Misc ---------------------------------------------------------------- * [Cargo docs are moving](https://github.com/rust-lang/rust/pull/43916) to [doc.rust-lang.org/cargo](https://doc.rust-lang.org/cargo) * [The rustdoc book is now available](https://github.com/rust-lang/rust/pull/43863) at [doc.rust-lang.org/rustdoc](https://doc.rust-lang.org/rustdoc) * [Added a preview of RLS has been made available through rustup](https://github.com/rust-lang/rust/pull/44204) Install with `rustup component add rls-preview` * [`std::os` documentation for Unix, Linux, and Windows now appears on doc.rust-lang.org](https://github.com/rust-lang/rust/pull/43348) Previously only showed `std::os::unix`. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-71) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Changes in method matching against higher-ranked types](https://github.com/rust-lang/rust/pull/43880) This may cause breakage in subtyping corner cases. [A more in-depth explanation is available.](https://github.com/rust-lang/rust/issues/44224#issuecomment-330058902) * [rustc’s JSON error output’s byte position start at top of file.](https://github.com/rust-lang/rust/pull/42973) Was previously relative to the rustc’s internal `CodeMap` struct which required the unstable library `libsyntax` to correctly use. * [`unused_results` lint no longer ignores booleans](https://github.com/rust-lang/rust/pull/43728) [§](https://doc.rust-lang.org/stable/releases.html#version-1200-2017-08-31) Version 1.20.0 (2017-08-31) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-71) Language ------------------------------------------------------------------------ * [Associated constants are now stabilised.](https://github.com/rust-lang/rust/pull/42809) * [A lot of macro bugs are now fixed.](https://github.com/rust-lang/rust/pull/42913) [§](https://doc.rust-lang.org/stable/releases.html#compiler-71) Compiler ------------------------------------------------------------------------ * [Struct fields are now properly coerced to the expected field type.](https://github.com/rust-lang/rust/pull/42807) * [Enabled wasm LLVM backend](https://github.com/rust-lang/rust/pull/42571) WASM can now be built with the `wasm32-experimental-emscripten` target. * [Changed some of the error messages to be more helpful.](https://github.com/rust-lang/rust/pull/42033) * [Add support for RELRO(RELocation Read-Only) for platforms that support it.](https://github.com/rust-lang/rust/pull/43170) * [rustc now reports the total number of errors on compilation failure](https://github.com/rust-lang/rust/pull/43015) previously this was only the number of errors in the pass that failed. * [Expansion in rustc has been sped up 29x.](https://github.com/rust-lang/rust/pull/42533) * [added `msp430-none-elf` target.](https://github.com/rust-lang/rust/pull/43099) * [rustc will now suggest one-argument enum variant to fix type mismatch when applicable](https://github.com/rust-lang/rust/pull/43178) * [Fixes backtraces on Redox](https://github.com/rust-lang/rust/pull/43228) * [rustc now identifies different versions of same crate when absolute paths of different types match in an error message.](https://github.com/rust-lang/rust/pull/42826) [§](https://doc.rust-lang.org/stable/releases.html#libraries-72) Libraries -------------------------------------------------------------------------- * [Relaxed Debug constraints on `{HashMap,BTreeMap}::{Keys,Values}`.](https://github.com/rust-lang/rust/pull/42854) * [Impl `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Debug`, `Hash` for unsized tuples.](https://github.com/rust-lang/rust/pull/43011) * [Impl `fmt::{Display, Debug}` for `Ref`, `RefMut`, `MutexGuard`, `RwLockReadGuard`, `RwLockWriteGuard`](https://github.com/rust-lang/rust/pull/42822) * [Impl `Clone` for `DefaultHasher`.](https://github.com/rust-lang/rust/pull/42799) * [Impl `Sync` for `SyncSender`.](https://github.com/rust-lang/rust/pull/42397) * [Impl `FromStr` for `char`](https://github.com/rust-lang/rust/pull/42271) * [Fixed how `{f32, f64}::{is_sign_negative, is_sign_positive}` handles NaN.](https://github.com/rust-lang/rust/pull/42431) * [allow messages in the `unimplemented!()` macro.](https://github.com/rust-lang/rust/pull/42155) ie. `unimplemented!("Waiting for 1.21 to be stable")` * [`pub(restricted)` is now supported in the `thread_local!` macro.](https://github.com/rust-lang/rust/pull/43185) * [Upgrade to Unicode 10.0.0](https://github.com/rust-lang/rust/pull/42999) * [Reimplemented `{f32, f64}::{min, max}` in Rust instead of using CMath.](https://github.com/rust-lang/rust/pull/42430) * [Skip the main thread’s manual stack guard on Linux](https://github.com/rust-lang/rust/pull/43072) * [Iterator::nth for `ops::{Range, RangeFrom}` is now done in _O_(1) time](https://github.com/rust-lang/rust/pull/43077) * [`#[repr(align(N))]` attribute max number is now 2^31 - 1.](https://github.com/rust-lang/rust/pull/43097) This was previously 2^15. * [`{OsStr, Path}::Display` now avoids allocations where possible](https://github.com/rust-lang/rust/pull/42613) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-67) Stabilized APIs -------------------------------------------------------------------------------------- * [`CStr::into_c_string`](https://doc.rust-lang.org/std/ffi/struct.CStr.html#method.into_c_string) * [`CString::as_c_str`](https://doc.rust-lang.org/std/ffi/struct.CString.html#method.as_c_str) * [`CString::into_boxed_c_str`](https://doc.rust-lang.org/std/ffi/struct.CString.html#method.into_boxed_c_str) * [`Chain::get_mut`](https://doc.rust-lang.org/std/io/struct.Chain.html#method.get_mut) * [`Chain::get_ref`](https://doc.rust-lang.org/std/io/struct.Chain.html#method.get_ref) * [`Chain::into_inner`](https://doc.rust-lang.org/std/io/struct.Chain.html#method.into_inner) * [`Option::get_or_insert_with`](https://doc.rust-lang.org/std/option/enum.Option.html#method.get_or_insert_with) * [`Option::get_or_insert`](https://doc.rust-lang.org/std/option/enum.Option.html#method.get_or_insert) * [`OsStr::into_os_string`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.into_os_string) * [`OsString::into_boxed_os_str`](https://doc.rust-lang.org/std/ffi/struct.OsString.html#method.into_boxed_os_str) * [`Take::get_mut`](https://doc.rust-lang.org/std/io/struct.Take.html#method.get_mut) * [`Take::get_ref`](https://doc.rust-lang.org/std/io/struct.Take.html#method.get_ref) * [`Utf8Error::error_len`](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html#method.error_len) * [`char::EscapeDebug`](https://doc.rust-lang.org/std/char/struct.EscapeDebug.html) * [`char::escape_debug`](https://doc.rust-lang.org/std/primitive.char.html#method.escape_debug) * [`compile_error!`](https://doc.rust-lang.org/std/macro.compile_error.html) * [`f32::from_bits`](https://doc.rust-lang.org/std/primitive.f32.html#method.from_bits) * [`f32::to_bits`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_bits) * [`f64::from_bits`](https://doc.rust-lang.org/std/primitive.f64.html#method.from_bits) * [`f64::to_bits`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_bits) * [`mem::ManuallyDrop`](https://doc.rust-lang.org/std/mem/union.ManuallyDrop.html) * [`slice::sort_unstable_by_key`](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by_key) * [`slice::sort_unstable_by`](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by) * [`slice::sort_unstable`](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable) * [`str::from_boxed_utf8_unchecked`](https://doc.rust-lang.org/std/str/fn.from_boxed_utf8_unchecked.html) * [`str::as_bytes_mut`](https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes_mut) * [`str::as_bytes_mut`](https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes_mut) * [`str::from_utf8_mut`](https://doc.rust-lang.org/std/str/fn.from_utf8_mut.html) * [`str::from_utf8_unchecked_mut`](https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked_mut.html) * [`str::get_mut`](https://doc.rust-lang.org/std/primitive.str.html#method.get_mut) * [`str::get_unchecked_mut`](https://doc.rust-lang.org/std/primitive.str.html#method.get_unchecked_mut) * [`str::get_unchecked`](https://doc.rust-lang.org/std/primitive.str.html#method.get_unchecked) * [`str::get`](https://doc.rust-lang.org/std/primitive.str.html#method.get) * [`str::into_boxed_bytes`](https://doc.rust-lang.org/std/primitive.str.html#method.into_boxed_bytes) [§](https://doc.rust-lang.org/stable/releases.html#cargo-70) Cargo ------------------------------------------------------------------ * [Cargo API token location moved from `~/.cargo/config` to `~/.cargo/credentials`.](https://github.com/rust-lang/cargo/pull/3978) * [Cargo will now build `main.rs` binaries that are in sub-directories of `src/bin`.](https://github.com/rust-lang/cargo/pull/4214) ie. Having `src/bin/server/main.rs` and `src/bin/client/main.rs` generates `target/debug/server` and `target/debug/client` * [You can now specify version of a binary when installed through `cargo install` using `--vers`.](https://github.com/rust-lang/cargo/pull/4229) * [Added `--no-fail-fast` flag to cargo to run all benchmarks regardless of failure.](https://github.com/rust-lang/cargo/pull/4248) * [Changed the convention around which file is the crate root.](https://github.com/rust-lang/cargo/pull/4259) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-72) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Functions with `'static` in their return types will now not be as usable as if they were using lifetime parameters instead.](https://github.com/rust-lang/rust/pull/42417) * [The reimplementation of `{f32, f64}::is_sign_{negative, positive}` now takes the sign of NaN into account where previously didn’t.](https://github.com/rust-lang/rust/pull/42430) [§](https://doc.rust-lang.org/stable/releases.html#version-1190-2017-07-20) Version 1.19.0 (2017-07-20) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-72) Language ------------------------------------------------------------------------ * [Numeric fields can now be used for creating tuple structs.](https://github.com/rust-lang/rust/pull/41145) [RFC 1506](https://github.com/rust-lang/rfcs/pull/1506) For example `struct Point(u32, u32); let x = Point { 0: 7, 1: 0 };`. * [Macro recursion limit increased to 1024 from 64.](https://github.com/rust-lang/rust/pull/41676) * [Added lint for detecting unused macros.](https://github.com/rust-lang/rust/pull/41907) * [`loop` can now return a value with `break`.](https://github.com/rust-lang/rust/pull/42016) [RFC 1624](https://github.com/rust-lang/rfcs/pull/1624) For example: `let x = loop { break 7; };` * [C compatible `union`s are now available.](https://github.com/rust-lang/rust/pull/42068) [RFC 1444](https://github.com/rust-lang/rfcs/pull/1444) They can only contain `Copy` types and cannot have a `Drop` implementation. Example: `union Foo { bar: u8, baz: usize }` * [Non capturing closures can now be coerced into `fn`s,](https://github.com/rust-lang/rust/pull/42162) [RFC 1558](https://github.com/rust-lang/rfcs/pull/1558) Example: `let foo: fn(u8) -> u8 = |v: u8| { v };` [§](https://doc.rust-lang.org/stable/releases.html#compiler-72) Compiler ------------------------------------------------------------------------ * [Add support for bootstrapping the Rust compiler toolchain on Android.](https://github.com/rust-lang/rust/pull/41370) * [Change `arm-linux-androideabi` to correspond to the `armeabi` official ABI.](https://github.com/rust-lang/rust/pull/41656) If you wish to continue targeting the `armeabi-v7a` ABI you should use `--target armv7-linux-androideabi`. * [Fixed ICE when removing a source file between compilation sessions.](https://github.com/rust-lang/rust/pull/41873) * [Minor optimisation of string operations.](https://github.com/rust-lang/rust/pull/42037) * [Compiler error message is now `aborting due to previous error(s)` instead of `aborting due to N previous errors`](https://github.com/rust-lang/rust/pull/42150) This was previously inaccurate and would only count certain kinds of errors. * [The compiler now supports Visual Studio 2017](https://github.com/rust-lang/rust/pull/42225) * [The compiler is now built against LLVM 4.0.1 by default](https://github.com/rust-lang/rust/pull/42948) * [Added a lot](https://github.com/rust-lang/rust/pull/42264) of [new error codes](https://github.com/rust-lang/rust/pull/42302) * [Added `target-feature=+crt-static` option](https://github.com/rust-lang/rust/issues/37406) [RFC 1721](https://github.com/rust-lang/rfcs/pull/1721) Which allows libraries with C Run-time Libraries(CRT) to be statically linked. * [Fixed various ARM codegen bugs](https://github.com/rust-lang/rust/pull/42740) [§](https://doc.rust-lang.org/stable/releases.html#libraries-73) Libraries -------------------------------------------------------------------------- * [`String` now implements `FromIterator>` and `Extend>`](https://github.com/rust-lang/rust/pull/41449) * [`Vec` now implements `From<&mut [T]>`](https://github.com/rust-lang/rust/pull/41530) * [`Box<[u8]>` now implements `From>`](https://github.com/rust-lang/rust/pull/41258) * [`SplitWhitespace` now implements `Clone`](https://github.com/rust-lang/rust/pull/41659) * [`[u8]::reverse` is now 5x faster and `[u16]::reverse` is now 1.5x faster](https://github.com/rust-lang/rust/pull/41764) * [`eprint!` and `eprintln!` macros added to prelude.](https://github.com/rust-lang/rust/pull/41192) Same as the `print!` macros, but for printing to stderr. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-68) Stabilized APIs -------------------------------------------------------------------------------------- * [`OsString::shrink_to_fit`](https://doc.rust-lang.org/std/ffi/struct.OsString.html#method.shrink_to_fit) * [`cmp::Reverse`](https://doc.rust-lang.org/std/cmp/struct.Reverse.html) * [`Command::envs`](https://doc.rust-lang.org/std/process/struct.Command.html#method.envs) * [`thread::ThreadId`](https://doc.rust-lang.org/std/thread/struct.ThreadId.html) [§](https://doc.rust-lang.org/stable/releases.html#cargo-71) Cargo ------------------------------------------------------------------ * [Build scripts can now add environment variables to the environment the crate is being compiled in. Example: `println!("cargo:rustc-env=FOO=bar");`](https://github.com/rust-lang/cargo/pull/3929) * [Subcommands now replace the current process rather than spawning a new child process](https://github.com/rust-lang/cargo/pull/3970) * [Workspace members can now accept glob file patterns](https://github.com/rust-lang/cargo/pull/3979) * [Added `--all` flag to the `cargo bench` subcommand to run benchmarks of all the members in a given workspace.](https://github.com/rust-lang/cargo/pull/3988) * [Updated `libssh2-sys` to 0.2.6](https://github.com/rust-lang/cargo/pull/4008) * [Target directory path is now in the cargo metadata](https://github.com/rust-lang/cargo/pull/4022) * [Cargo no longer checks out a local working directory for the crates.io index](https://github.com/rust-lang/cargo/pull/4026) This should provide smaller file size for the registry, and improve cloning times, especially on Windows machines. * [Added an `--exclude` option for excluding certain packages when using the `--all` option](https://github.com/rust-lang/cargo/pull/4031) * [Cargo will now automatically retry when receiving a 5xx error from crates.io](https://github.com/rust-lang/cargo/pull/4032) * [The `--features` option now accepts multiple comma or space delimited values.](https://github.com/rust-lang/cargo/pull/4084) * [Added support for custom target specific runners](https://github.com/rust-lang/cargo/pull/3954) [§](https://doc.rust-lang.org/stable/releases.html#misc-34) Misc ---------------------------------------------------------------- * [Added `rust-windbg.cmd`](https://github.com/rust-lang/rust/pull/39983) for loading rust `.natvis` files in the Windows Debugger. * [Rust will now release XZ compressed packages](https://github.com/rust-lang/rust-installer/pull/57) * [rustup will now prefer to download rust packages with XZ compression](https://github.com/rust-lang-nursery/rustup.rs/pull/1100) over GZip packages. * [Added the ability to escape `#` in rust documentation](https://github.com/rust-lang/rust/pull/41785) By adding additional `#`’s ie. `##` is now `#` [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-73) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`MutexGuard` may only be `Sync` if `T` is `Sync`.](https://github.com/rust-lang/rust/pull/41624) * [`-Z` flags are now no longer allowed to be used on the stable compiler.](https://github.com/rust-lang/rust/pull/41751) This has been a warning for a year previous to this. * [As a result of the `-Z` flag change, the `cargo-check` plugin no longer works](https://github.com/rust-lang/rust/issues/42844) . Users should migrate to the built-in `check` command, which has been available since 1.16. * [Ending a float literal with `._` is now a hard error. Example: `42._` .](https://github.com/rust-lang/rust/pull/41946) * [Any use of a private `extern crate` outside of its module is now a hard error.](https://github.com/rust-lang/rust/issues/36886) This was previously a warning. * [`use ::self::foo;` is now a hard error.](https://github.com/rust-lang/rust/issues/36888) `self` paths are always relative while the `::` prefix makes a path absolute, but was ignored and the path was relative regardless. * [Floating point constants in match patterns is now a hard error](https://github.com/rust-lang/rust/issues/36890) This was previously a warning. * [Struct or enum constants that don’t derive `PartialEq` & `Eq` used match patterns is now a hard error](https://github.com/rust-lang/rust/issues/36891) This was previously a warning. * [Lifetimes named `'_` are no longer allowed.](https://github.com/rust-lang/rust/issues/36892) This was previously a warning. * [From the pound escape, lines consisting of multiple `#`s are now visible](https://github.com/rust-lang/rust/pull/41785) * [It is an error to re-export private enum variants](https://github.com/rust-lang/rust/issues/42460) . This is known to break a number of crates that depend on an older version of mustache. * [On Windows, if `VCINSTALLDIR` is set incorrectly, `rustc` will try to use it to find the linker, and the build will fail where it did not previously](https://github.com/rust-lang/rust/issues/42607) [§](https://doc.rust-lang.org/stable/releases.html#version-1180-2017-06-08) Version 1.18.0 (2017-06-08) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-73) Language ------------------------------------------------------------------------ * [Stabilize pub(restricted)](https://github.com/rust-lang/rust/pull/40556) `pub` can now accept a module path to make the item visible to just that module tree. Also accepts the keyword `crate` to make something public to the whole crate but not users of the library. Example: `pub(crate) mod utils;`. [RFC 1422](https://github.com/rust-lang/rfcs/blob/master/text/1422-pub-restricted.md) . * [Stabilize `#![windows_subsystem]` attribute](https://github.com/rust-lang/rust/pull/40870) conservative exposure of the `/SUBSYSTEM` linker flag on Windows platforms. [RFC 1665](https://github.com/rust-lang/rfcs/blob/master/text/1665-windows-subsystem.md) . * [Refactor of trait object type parsing](https://github.com/rust-lang/rust/pull/40043) Now `ty` in macros can accept types like `Write + Send`, trailing `+` are now supported in trait objects, and better error reporting for trait objects starting with `?Sized`. * [0e+10 is now a valid floating point literal](https://github.com/rust-lang/rust/pull/40589) * [Now warns if you bind a lifetime parameter to ’static](https://github.com/rust-lang/rust/pull/40734) * [Tuples, Enum variant fields, and structs with no `repr` attribute or with `#[repr(Rust)]` are reordered to minimize padding and produce a smaller representation in some cases.](https://github.com/rust-lang/rust/pull/40377) [§](https://doc.rust-lang.org/stable/releases.html#compiler-73) Compiler ------------------------------------------------------------------------ * [rustc can now emit mir with `--emit mir`](https://github.com/rust-lang/rust/pull/39891) * [Improved LLVM IR for trivial functions](https://github.com/rust-lang/rust/pull/40367) * [Added explanation for E0090(Wrong number of lifetimes are supplied)](https://github.com/rust-lang/rust/pull/40723) * [rustc compilation is now 15%-20% faster](https://github.com/rust-lang/rust/pull/41469) Thanks to optimisation opportunities found through profiling * [Improved backtrace formatting when panicking](https://github.com/rust-lang/rust/pull/38165) [§](https://doc.rust-lang.org/stable/releases.html#libraries-74) Libraries -------------------------------------------------------------------------- * [Specialized `Vec::from_iter` being passed `vec::IntoIter`](https://github.com/rust-lang/rust/pull/40731) if the iterator hasn’t been advanced the original `Vec` is reassembled with no actual iteration or reallocation. * [Simplified HashMap Bucket interface](https://github.com/rust-lang/rust/pull/40561) provides performance improvements for iterating and cloning. * [Specialize Vec::from\_elem to use calloc](https://github.com/rust-lang/rust/pull/40409) * [Fixed Race condition in fs::create\_dir\_all](https://github.com/rust-lang/rust/pull/39799) * [No longer caching stdio on Windows](https://github.com/rust-lang/rust/pull/40516) * [Optimized insertion sort in slice](https://github.com/rust-lang/rust/pull/40807) insertion sort in some cases 2.50%~ faster and in one case now 12.50% faster. * [Optimized `AtomicBool::fetch_nand`](https://github.com/rust-lang/rust/pull/41143) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-69) Stabilized APIs -------------------------------------------------------------------------------------- * [`Child::try_wait`](https://doc.rust-lang.org/std/process/struct.Child.html#method.try_wait) * [`HashMap::retain`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.retain) * [`HashSet::retain`](https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.retain) * [`PeekMut::pop`](https://doc.rust-lang.org/std/collections/binary_heap/struct.PeekMut.html#method.pop) * [`TcpStream::peek`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.peek) * [`UdpSocket::peek`](https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.peek) * [`UdpSocket::peek_from`](https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.peek_from) [§](https://doc.rust-lang.org/stable/releases.html#cargo-72) Cargo ------------------------------------------------------------------ * [Added partial Pijul support](https://github.com/rust-lang/cargo/pull/3842) Pijul is a version control system in Rust. You can now create new cargo projects with Pijul using `cargo new --vcs pijul` * [Now always emits build script warnings for crates that fail to build](https://github.com/rust-lang/cargo/pull/3847) * [Added Android build support](https://github.com/rust-lang/cargo/pull/3885) * [Added `--bins` and `--tests` flags](https://github.com/rust-lang/cargo/pull/3901) now you can build all programs of a certain type, for example `cargo build --bins` will build all binaries. * [Added support for haiku](https://github.com/rust-lang/cargo/pull/3952) [§](https://doc.rust-lang.org/stable/releases.html#misc-35) Misc ---------------------------------------------------------------- * [rustdoc can now use pulldown-cmark with the `--enable-commonmark` flag](https://github.com/rust-lang/rust/pull/40338) * [Rust now uses the official cross compiler for NetBSD](https://github.com/rust-lang/rust/pull/40612) * [rustdoc now accepts `#` at the start of files](https://github.com/rust-lang/rust/pull/40828) * [Fixed jemalloc support for musl](https://github.com/rust-lang/rust/pull/41168) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-74) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Changes to how the `0` flag works in format!](https://github.com/rust-lang/rust/pull/40241) Padding zeroes are now always placed after the sign if it exists and before the digits. With the `#` flag the zeroes are placed after the prefix and before the digits. * [Due to the struct field optimisation](https://github.com/rust-lang/rust/pull/40377) , using `transmute` on structs that have no `repr` attribute or `#[repr(Rust)]` will no longer work. This has always been undefined behavior, but is now more likely to break in practice. * [The refactor of trait object type parsing](https://github.com/rust-lang/rust/pull/40043) fixed a bug where `+` was receiving the wrong priority parsing things like `&for<'a> Tr<'a> + Send` as `&(for<'a> Tr<'a> + Send)` instead of `(&for<'a> Tr<'a>) + Send` * [Overlapping inherent `impl`s are now a hard error](https://github.com/rust-lang/rust/pull/40728) * [`PartialOrd` and `Ord` must agree on the ordering.](https://github.com/rust-lang/rust/issues/41270) * [`rustc main.rs -o out --emit=asm,llvm-ir`](https://github.com/rust-lang/rust/pull/41085) Now will output `out.asm` and `out.ll` instead of only one of the filetypes. * [calling a function that returns `Self` will no longer work](https://github.com/rust-lang/rust/issues/41805) when the size of `Self` cannot be statically determined. * [rustc now builds with a “pthreads” flavour of MinGW for Windows GNU](https://github.com/rust-lang/rust/pull/40805) this has caused a few regressions namely: * Changed the link order of local static/dynamic libraries (respecting the order on given rather than having the compiler reorder). * Changed how MinGW is linked, native code linked to dynamic libraries may require manually linking to the gcc support library (for the native code itself) [§](https://doc.rust-lang.org/stable/releases.html#version-1170-2017-04-27) Version 1.17.0 (2017-04-27) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-74) Language ------------------------------------------------------------------------ * [The lifetime of statics and consts defaults to `'static`](https://github.com/rust-lang/rust/pull/39265) . [RFC 1623](https://github.com/rust-lang/rfcs/blob/master/text/1623-static.md) * [Fields of structs may be initialized without duplicating the field/variable names](https://github.com/rust-lang/rust/pull/39761) . [RFC 1682](https://github.com/rust-lang/rfcs/blob/master/text/1682-field-init-shorthand.md) * [`Self` may be included in the `where` clause of `impls`](https://github.com/rust-lang/rust/issues/38864) . [RFC 1647](https://github.com/rust-lang/rfcs/blob/master/text/1647-allow-self-in-where-clauses.md) * [When coercing to an unsized type lifetimes must be equal](https://github.com/rust-lang/rust/pull/40319) . That is, there is no subtyping between `T` and `U` when `T: Unsize`. For example, coercing `&mut [&'a X; N]` to `&mut [&'b X]` requires `'a` be equal to `'b`. Soundness fix. * [Values passed to the indexing operator, `[]`, automatically coerce](https://github.com/rust-lang/rust/pull/40166) * [Static variables may contain references to other statics](https://github.com/rust-lang/rust/pull/40027) [§](https://doc.rust-lang.org/stable/releases.html#compiler-74) Compiler ------------------------------------------------------------------------ * [Exit quickly on only `--emit dep-info`](https://github.com/rust-lang/rust/pull/40336) * [Make `-C relocation-model` more correctly determine whether the linker creates a position-independent executable](https://github.com/rust-lang/rust/pull/40245) * [Add `-C overflow-checks` to directly control whether integer overflow panics](https://github.com/rust-lang/rust/pull/40037) * [The rustc type checker now checks items on demand instead of in a single in-order pass](https://github.com/rust-lang/rust/pull/40008) . This is mostly an internal refactoring in support of future work, including incremental type checking, but also resolves [RFC 1647](https://github.com/rust-lang/rfcs/blob/master/text/1647-allow-self-in-where-clauses.md) , allowing `Self` to appear in `impl` `where` clauses. * [Optimize vtable loads](https://github.com/rust-lang/rust/pull/39995) * [Turn off vectorization for Emscripten targets](https://github.com/rust-lang/rust/pull/39990) * [Provide suggestions for unknown macros imported with `use`](https://github.com/rust-lang/rust/pull/39953) * [Fix ICEs in path resolution](https://github.com/rust-lang/rust/pull/39939) * [Strip exception handling code on Emscripten when `panic=abort`](https://github.com/rust-lang/rust/pull/39193) * [Add clearer error message using `&str + &str`](https://github.com/rust-lang/rust/pull/39116) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-70) Stabilized APIs -------------------------------------------------------------------------------------- * [`Arc::into_raw`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.into_raw) * [`Arc::from_raw`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.from_raw) * [`Arc::ptr_eq`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.ptr_eq) * [`Rc::into_raw`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.into_raw) * [`Rc::from_raw`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.from_raw) * [`Rc::ptr_eq`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.ptr_eq) * [`Ordering::then`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.then) * [`Ordering::then_with`](https://doc.rust-lang.org/std/cmp/enum.Ordering.html#method.then_with) * [`BTreeMap::range`](https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.range) * [`BTreeMap::range_mut`](https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.range_mut) * [`collections::Bound`](https://doc.rust-lang.org/std/collections/enum.Bound.html) * [`process::abort`](https://doc.rust-lang.org/std/process/fn.abort.html) * [`ptr::read_unaligned`](https://doc.rust-lang.org/std/ptr/fn.read_unaligned.html) * [`ptr::write_unaligned`](https://doc.rust-lang.org/std/ptr/fn.write_unaligned.html) * [`Result::expect_err`](https://doc.rust-lang.org/std/result/enum.Result.html#method.expect_err) * [`Cell::swap`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.swap) * [`Cell::replace`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.replace) * [`Cell::into_inner`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.into_inner) * [`Cell::take`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.take) [§](https://doc.rust-lang.org/stable/releases.html#libraries-75) Libraries -------------------------------------------------------------------------- * [`BTreeMap` and `BTreeSet` can iterate over ranges](https://github.com/rust-lang/rust/issues/27787) * [`Cell` can store non-`Copy` types](https://github.com/rust-lang/rust/pull/39793) . [RFC 1651](https://github.com/rust-lang/rfcs/blob/master/text/1651-movecell.md) * [`String` implements `FromIterator<&char>`](https://github.com/rust-lang/rust/pull/40028) * `Box` [implements](https://github.com/rust-lang/rust/pull/40009) a number of new conversions: `From> for String`, `From> for Vec`, `From> for CString`, `From> for OsString`, `From> for PathBuf`, `Into> for String`, `Into> for Vec`, `Into> for CString`, `Into> for OsString`, `Into> for PathBuf`, `Default for Box`, `Default for Box`, `Default for Box`, `From<&CStr> for Box`, `From<&OsStr> for Box`, `From<&Path> for Box` * [`ffi::FromBytesWithNulError` implements `Error` and `Display`](https://github.com/rust-lang/rust/pull/39960) * [Specialize `PartialOrd for [A] where A: Ord`](https://github.com/rust-lang/rust/pull/39642) * [Slightly optimize `slice::sort`](https://github.com/rust-lang/rust/pull/39538) * [Add `ToString` trait specialization for `Cow<'a, str>` and `String`](https://github.com/rust-lang/rust/pull/39440) * [`Box<[T]>` implements `From<&[T]> where T: Copy`, `Box` implements `From<&str>`](https://github.com/rust-lang/rust/pull/39438) * [`IpAddr` implements `From` for various arrays. `SocketAddr` implements `From<(I, u16)> where I: Into`](https://github.com/rust-lang/rust/pull/39372) * [`format!` estimates the needed capacity before writing a string](https://github.com/rust-lang/rust/pull/39356) * [Support unprivileged symlink creation in Windows](https://github.com/rust-lang/rust/pull/38921) * [`PathBuf` implements `Default`](https://github.com/rust-lang/rust/pull/38764) * [Implement `PartialEq<[A]>` for `VecDeque`](https://github.com/rust-lang/rust/pull/38661) * [`HashMap` resizes adaptively](https://github.com/rust-lang/rust/pull/38368) to guard against DOS attacks and poor hash functions. [§](https://doc.rust-lang.org/stable/releases.html#cargo-73) Cargo ------------------------------------------------------------------ * [Add `cargo check --all`](https://github.com/rust-lang/cargo/pull/3731) * [Add an option to ignore SSL revocation checking](https://github.com/rust-lang/cargo/pull/3699) * [Add `cargo run --package`](https://github.com/rust-lang/cargo/pull/3691) * [Add `required_features`](https://github.com/rust-lang/cargo/pull/3667) * [Assume `build.rs` is a build script](https://github.com/rust-lang/cargo/pull/3664) * [Find workspace via `workspace_root` link in containing member](https://github.com/rust-lang/cargo/pull/3562) [§](https://doc.rust-lang.org/stable/releases.html#misc-36) Misc ---------------------------------------------------------------- * [Documentation is rendered with mdbook instead of the obsolete, in-tree `rustbook`](https://github.com/rust-lang/rust/pull/39633) * [The “Unstable Book” documents nightly-only features](https://doc.rust-lang.org/unstable-book/) * [Improve the style of the sidebar in rustdoc output](https://github.com/rust-lang/rust/pull/40265) * [Configure build correctly on 64-bit CPU’s with the armhf ABI](https://github.com/rust-lang/rust/pull/40261) * [Fix MSP430 breakage due to `i128`](https://github.com/rust-lang/rust/pull/40257) * [Preliminary Solaris/SPARCv9 support](https://github.com/rust-lang/rust/pull/39903) * [`rustc` is linked statically on Windows MSVC targets](https://github.com/rust-lang/rust/pull/39837) , allowing it to run without installing the MSVC runtime. * [`rustdoc --test` includes file names in test names](https://github.com/rust-lang/rust/pull/39788) * This release includes builds of `std` for `sparc64-unknown-linux-gnu`, `aarch64-unknown-linux-fuchsia`, and `x86_64-unknown-linux-fuchsia`. * [Initial support for `aarch64-unknown-freebsd`](https://github.com/rust-lang/rust/pull/39491) * [Initial support for `i686-unknown-netbsd`](https://github.com/rust-lang/rust/pull/39426) * [This release no longer includes the old makefile build system](https://github.com/rust-lang/rust/pull/39431) . Rust is built with a custom build system, written in Rust, and with Cargo. * [Add Debug implementations for libcollection structs](https://github.com/rust-lang/rust/pull/39002) * [`TypeId` implements `PartialOrd` and `Ord`](https://github.com/rust-lang/rust/pull/38981) * [`--test-threads=0` produces an error](https://github.com/rust-lang/rust/pull/38945) * [`rustup` installs documentation by default](https://github.com/rust-lang/rust/pull/40526) * [The Rust source includes NatVis visualizations](https://github.com/rust-lang/rust/pull/39843) . These can be used by WinDbg and Visual Studio to improve the debugging experience. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-75) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Rust 1.17 does not correctly detect the MSVC 2017 linker](https://github.com/rust-lang/rust/issues/38584) . As a workaround, either use MSVC 2015 or run vcvars.bat. * [When coercing to an unsized type lifetimes must be equal](https://github.com/rust-lang/rust/pull/40319) . That is, disallow subtyping between `T` and `U` when `T: Unsize`, e.g. coercing `&mut [&'a X; N]` to `&mut [&'b X]` requires `'a` be equal to `'b`. Soundness fix. * [`format!` and `Display::to_string` panic if an underlying formatting implementation returns an error](https://github.com/rust-lang/rust/pull/40117) . Previously the error was silently ignored. It is incorrect for `write_fmt` to return an error when writing to a string. * [In-tree crates are verified to be unstable](https://github.com/rust-lang/rust/pull/39851) . Previously, some minor crates were marked stable and could be accessed from the stable toolchain. * [Rust git source no longer includes vendored crates](https://github.com/rust-lang/rust/pull/39728) . Those that need to build with vendored crates should build from release tarballs. * [Fix inert attributes from `proc_macro_derives`](https://github.com/rust-lang/rust/pull/39572) * [During crate resolution, rustc prefers a crate in the sysroot if two crates are otherwise identical](https://github.com/rust-lang/rust/pull/39518) . Unlikely to be encountered outside the Rust build system. * [Fixed bugs around how type inference interacts with dead-code](https://github.com/rust-lang/rust/pull/39485) . The existing code generally ignores the type of dead-code unless a type-hint is provided; this can cause surprising inference interactions particularly around defaulting. The new code uniformly ignores the result type of dead-code. * [Tuple-struct constructors with private fields are no longer visible](https://github.com/rust-lang/rust/pull/38932) * [Lifetime parameters that do not appear in the arguments are now considered early-bound](https://github.com/rust-lang/rust/pull/38897) , resolving a soundness bug (#[32330](https://github.com/rust-lang/rust/issues/32330) ). The `hr_lifetime_in_assoc_type` future-compatibility lint has been in effect since April of 2016. * [rustdoc: fix doctests with non-feature crate attributes](https://github.com/rust-lang/rust/pull/38161) * [Make transmuting from fn item types to pointer-sized types a hard error](https://github.com/rust-lang/rust/pull/34198) [§](https://doc.rust-lang.org/stable/releases.html#version-1160-2017-03-16) Version 1.16.0 (2017-03-16) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-75) Language ------------------------------------------------------------------------ * [The compiler’s `dead_code` lint now accounts for type aliases](https://github.com/rust-lang/rust/pull/38051) . * [Uninhabitable enums (those without any variants) no longer permit wildcard match patterns](https://github.com/rust-lang/rust/pull/38069) * [Clean up semantics of `self` in an import list](https://github.com/rust-lang/rust/pull/38313) * [`Self` may appear in `impl` headers](https://github.com/rust-lang/rust/pull/38920) * [`Self` may appear in struct expressions](https://github.com/rust-lang/rust/pull/39282) [§](https://doc.rust-lang.org/stable/releases.html#compiler-75) Compiler ------------------------------------------------------------------------ * [`rustc` now supports `--emit=metadata`, which causes rustc to emit a `.rmeta` file containing only crate metadata](https://github.com/rust-lang/rust/pull/38571) . This can be used by tools like the Rust Language Service to perform metadata-only builds. * [Levenshtein based typo suggestions now work in most places, while previously they worked only for fields and sometimes for local variables](https://github.com/rust-lang/rust/pull/38927) . Together with the overhaul of “no resolution”/“unexpected resolution” errors (#[38154](https://github.com/rust-lang/rust/pull/38154) ) they result in large and systematic improvement in resolution diagnostics. * [Fix `transmute::` where `T` requires a bigger alignment than `U`](https://github.com/rust-lang/rust/pull/38670) * [rustc: use -Xlinker when specifying an rpath with ‘,’ in it](https://github.com/rust-lang/rust/pull/38798) * [`rustc` no longer attempts to provide “consider using an explicit lifetime” suggestions](https://github.com/rust-lang/rust/pull/37057) . They were inaccurate. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-71) Stabilized APIs -------------------------------------------------------------------------------------- * [`VecDeque::truncate`](https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html#method.truncate) * [`VecDeque::resize`](https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html#method.resize) * [`String::insert_str`](https://doc.rust-lang.org/std/string/struct.String.html#method.insert_str) * [`Duration::checked_add`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_add) * [`Duration::checked_sub`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_sub) * [`Duration::checked_div`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_div) * [`Duration::checked_mul`](https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_mul) * [`str::replacen`](https://doc.rust-lang.org/std/primitive.str.html#method.replacen) * [`str::repeat`](https://doc.rust-lang.org/std/primitive.str.html#method.repeat) * [`SocketAddr::is_ipv4`](https://doc.rust-lang.org/std/net/enum.SocketAddr.html#method.is_ipv4) * [`SocketAddr::is_ipv6`](https://doc.rust-lang.org/std/net/enum.SocketAddr.html#method.is_ipv6) * [`IpAddr::is_ipv4`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv4) * [`IpAddr::is_ipv6`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv6) * [`Vec::dedup_by`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup_by) * [`Vec::dedup_by_key`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup_by_key) * [`Result::unwrap_or_default`](https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or_default) * [`<*const T>::wrapping_offset`](https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset) * [`<*mut T>::wrapping_offset`](https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset-1) * `CommandExt::creation_flags` * [`File::set_permissions`](https://doc.rust-lang.org/std/fs/struct.File.html#method.set_permissions) * [`String::split_off`](https://doc.rust-lang.org/std/string/struct.String.html#method.split_off) [§](https://doc.rust-lang.org/stable/releases.html#libraries-76) Libraries -------------------------------------------------------------------------- * [`[T]::binary_search` and `[T]::binary_search_by_key` now take their argument by `Borrow` parameter](https://github.com/rust-lang/rust/pull/37761) * [All public types in std implement `Debug`](https://github.com/rust-lang/rust/pull/38006) * [`IpAddr` implements `From` and `From`](https://github.com/rust-lang/rust/pull/38327) * [`Ipv6Addr` implements `From<[u16; 8]>`](https://github.com/rust-lang/rust/pull/38131) * [Ctrl-Z returns from `Stdin.read()` when reading from the console on Windows](https://github.com/rust-lang/rust/pull/38274) * [std: Fix partial writes in `LineWriter`](https://github.com/rust-lang/rust/pull/38062) * [std: Clamp max read/write sizes on Unix](https://github.com/rust-lang/rust/pull/38622) * [Use more specific panic message for `&str` slicing errors](https://github.com/rust-lang/rust/pull/38066) * [`TcpListener::set_only_v6` is deprecated](https://github.com/rust-lang/rust/pull/38304) . This functionality cannot be achieved in std currently. * [`writeln!`, like `println!`, now accepts a form with no string or formatting arguments, to just print a newline](https://github.com/rust-lang/rust/pull/38469) * [Implement `iter::Sum` and `iter::Product` for `Result`](https://github.com/rust-lang/rust/pull/38580) * [Reduce the size of static data in `std_unicode::tables`](https://github.com/rust-lang/rust/pull/38781) * [`char::EscapeDebug`, `EscapeDefault`, `EscapeUnicode`, `CaseMappingIter`, `ToLowercase`, `ToUppercase`, implement `Display`](https://github.com/rust-lang/rust/pull/38909) * [`Duration` implements `Sum`](https://github.com/rust-lang/rust/pull/38712) * [`String` implements `ToSocketAddrs`](https://github.com/rust-lang/rust/pull/39048) [§](https://doc.rust-lang.org/stable/releases.html#cargo-74) Cargo ------------------------------------------------------------------ * [The `cargo check` command does a type check of a project without building it](https://github.com/rust-lang/cargo/pull/3296) * [crates.io will display CI badges from Travis and AppVeyor, if specified in Cargo.toml](https://github.com/rust-lang/cargo/pull/3546) * [crates.io will display categories listed in Cargo.toml](https://github.com/rust-lang/cargo/pull/3301) * [Compilation profiles accept integer values for `debug`, in addition to `true` and `false`. These are passed to `rustc` as the value to `-C debuginfo`](https://github.com/rust-lang/cargo/pull/3534) * [Implement `cargo --version --verbose`](https://github.com/rust-lang/cargo/pull/3604) * [All builds now output ‘dep-info’ build dependencies compatible with make and ninja](https://github.com/rust-lang/cargo/pull/3557) * [Build all workspace members with `build --all`](https://github.com/rust-lang/cargo/pull/3511) * [Document all workspace members with `doc --all`](https://github.com/rust-lang/cargo/pull/3515) * [Path deps outside workspace are not members](https://github.com/rust-lang/cargo/pull/3443) [§](https://doc.rust-lang.org/stable/releases.html#misc-37) Misc ---------------------------------------------------------------- * [`rustdoc` has a `--sysroot` argument that, like `rustc`, specifies the path to the Rust implementation](https://github.com/rust-lang/rust/pull/38589) * [The `armv7-linux-androideabi` target no longer enables NEON extensions, per Google’s ABI guide](https://github.com/rust-lang/rust/pull/38413) * [The stock standard library can be compiled for Redox OS](https://github.com/rust-lang/rust/pull/38401) * [Rust has initial SPARC support](https://github.com/rust-lang/rust/pull/38726) . Tier 3. No builds available. * [Rust has experimental support for Nvidia PTX](https://github.com/rust-lang/rust/pull/38559) . Tier 3. No builds available. * [Fix backtraces on i686-pc-windows-gnu by disabling FPO](https://github.com/rust-lang/rust/pull/39379) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-76) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Uninhabitable enums (those without any variants) no longer permit wildcard match patterns](https://github.com/rust-lang/rust/pull/38069) * In this release, references to uninhabited types can not be pattern-matched. This was accidentally allowed in 1.15. * [The compiler’s `dead_code` lint now accounts for type aliases](https://github.com/rust-lang/rust/pull/38051) . * [Ctrl-Z returns from `Stdin.read()` when reading from the console on Windows](https://github.com/rust-lang/rust/pull/38274) * [Clean up semantics of `self` in an import list](https://github.com/rust-lang/rust/pull/38313) * Reimplemented lifetime elision. This change was almost entirely compatible with existing code, but it did close a number of small bugs and loopholes, as well as being more accepting in some other [cases](https://github.com/rust-lang/rust/issues/41105) . [§](https://doc.rust-lang.org/stable/releases.html#version-1151-2017-02-09) Version 1.15.1 (2017-02-09) ======================================================================================================= * [Fix IntoIter::as\_mut\_slice’s signature](https://github.com/rust-lang/rust/pull/39466) * [Compile compiler builtins with `-fPIC` on 32-bit platforms](https://github.com/rust-lang/rust/pull/39523) [§](https://doc.rust-lang.org/stable/releases.html#version-1150-2017-02-02) Version 1.15.0 (2017-02-02) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-76) Language ------------------------------------------------------------------------ * Basic procedural macros allowing custom `#[derive]`, aka “macros 1.1”, are stable. This allows popular code-generating crates like Serde and Diesel to work ergonomically. [RFC 1681](https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md) . * [Tuple structs may be empty. Unary and empty tuple structs may be instantiated with curly braces](https://github.com/rust-lang/rust/pull/36868) . Part of [RFC 1506](https://github.com/rust-lang/rfcs/pull/1506) . * [A number of minor changes to name resolution have been activated](https://github.com/rust-lang/rust/pull/37127) . They add up to more consistent semantics, allowing for future evolution of Rust macros. Specified in [RFC 1560](https://github.com/rust-lang/rfcs/blob/master/text/1560-name-resolution.md) , see its section on [“changes”](https://github.com/rust-lang/rfcs/blob/master/text/1560-name-resolution.md#changes-to-name-resolution-rules) for details of what is different. The breaking changes here have been transitioned through the [`legacy_imports`](https://github.com/rust-lang/rust/pull/38271) lint since 1.14, with no known regressions. * [In `macro_rules`, `path` fragments can now be parsed as type parameter bounds](https://github.com/rust-lang/rust/pull/38279) * [`?Sized` can be used in `where` clauses](https://github.com/rust-lang/rust/pull/37791) * [There is now a limit on the size of monomorphized types and it can be modified with the `#![type_size_limit]` crate attribute, similarly to the `#![recursion_limit]` attribute](https://github.com/rust-lang/rust/pull/37789) [§](https://doc.rust-lang.org/stable/releases.html#compiler-76) Compiler ------------------------------------------------------------------------ * [On Windows, the compiler will apply dllimport attributes when linking to extern functions](https://github.com/rust-lang/rust/pull/37973) . Additional attributes and flags can control which library kind is linked and its name. [RFC 1717](https://github.com/rust-lang/rfcs/blob/master/text/1717-dllimport.md) . * [Rust-ABI symbols are no longer exported from cdylibs](https://github.com/rust-lang/rust/pull/38117) * [The `--test` flag works with procedural macro crates](https://github.com/rust-lang/rust/pull/38107) * [Fix `extern "aapcs" fn` ABI](https://github.com/rust-lang/rust/pull/37814) * [The `-C no-stack-check` flag is deprecated](https://github.com/rust-lang/rust/pull/37636) . It does nothing. * [The `format!` expander recognizes incorrect `printf` and shell-style formatting directives and suggests the correct format](https://github.com/rust-lang/rust/pull/37613) . * [Only report one error for all unused imports in an import list](https://github.com/rust-lang/rust/pull/37456) [§](https://doc.rust-lang.org/stable/releases.html#compiler-performance) Compiler Performance --------------------------------------------------------------------------------------------- * [Avoid unnecessary `mk_ty` calls in `Ty::super_fold_with`](https://github.com/rust-lang/rust/pull/37705) * [Avoid more unnecessary `mk_ty` calls in `Ty::super_fold_with`](https://github.com/rust-lang/rust/pull/37979) * [Don’t clone in `UnificationTable::probe`](https://github.com/rust-lang/rust/pull/37848) * [Remove `scope_auxiliary` to cut RSS by 10%](https://github.com/rust-lang/rust/pull/37764) * [Use small vectors in type walker](https://github.com/rust-lang/rust/pull/37760) * [Macro expansion performance was improved](https://github.com/rust-lang/rust/pull/37701) * [Change `HirVec>` to `HirVec` in `hir::Expr`](https://github.com/rust-lang/rust/pull/37642) * [Replace FNV with a faster hash function](https://github.com/rust-lang/rust/pull/37229) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-72) Stabilized APIs -------------------------------------------------------------------------------------- * [`std::iter::Iterator::min_by`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min_by) * [`std::iter::Iterator::max_by`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max_by) * [`std::os::*::fs::FileExt`](https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html) * [`std::sync::atomic::Atomic*::get_mut`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU8.html#method.get_mut) * [`std::sync::atomic::Atomic*::into_inner`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU8.html#method.into_inner) * [`std::vec::IntoIter::as_slice`](https://doc.rust-lang.org/std/vec/struct.IntoIter.html#method.as_slice) * [`std::vec::IntoIter::as_mut_slice`](https://doc.rust-lang.org/std/vec/struct.IntoIter.html#method.as_mut_slice) * [`std::sync::mpsc::Receiver::try_iter`](https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.try_iter) * [`std::os::unix::process::CommandExt::before_exec`](https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.before_exec) * [`std::rc::Rc::strong_count`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.strong_count) * [`std::rc::Rc::weak_count`](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.weak_count) * [`std::sync::Arc::strong_count`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.strong_count) * [`std::sync::Arc::weak_count`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.weak_count) * [`std::char::encode_utf8`](https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf8) * [`std::char::encode_utf16`](https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf16) * [`std::cell::Ref::clone`](https://doc.rust-lang.org/std/cell/struct.Ref.html#method.clone) * [`std::io::Take::into_inner`](https://doc.rust-lang.org/std/io/struct.Take.html#method.into_inner) [§](https://doc.rust-lang.org/stable/releases.html#libraries-77) Libraries -------------------------------------------------------------------------- * [The standard sorting algorithm has been rewritten for dramatic performance improvements](https://github.com/rust-lang/rust/pull/38192) . It is a hybrid merge sort, drawing influences from Timsort. Previously it was a naive merge sort. * [`Iterator::nth` no longer has a `Sized` bound](https://github.com/rust-lang/rust/pull/38134) * [`Extend<&T>` is specialized for `Vec` where `T: Copy`](https://github.com/rust-lang/rust/pull/38182) to improve performance. * [`chars().count()` is much faster](https://github.com/rust-lang/rust/pull/37888) and so are [`chars().last()` and `char_indices().last()`](https://github.com/rust-lang/rust/pull/37882) * [Fix ARM Objective-C ABI in `std::env::args`](https://github.com/rust-lang/rust/pull/38146) * [Chinese characters display correctly in `fmt::Debug`](https://github.com/rust-lang/rust/pull/37855) * [Derive `Default` for `Duration`](https://github.com/rust-lang/rust/pull/37699) * [Support creation of anonymous pipes on WinXP/2k](https://github.com/rust-lang/rust/pull/37677) * [`mpsc::RecvTimeoutError` implements `Error`](https://github.com/rust-lang/rust/pull/37527) * [Don’t pass overlapped handles to processes](https://github.com/rust-lang/rust/pull/38835) [§](https://doc.rust-lang.org/stable/releases.html#cargo-75) Cargo ------------------------------------------------------------------ * [In this release, Cargo build scripts no longer have access to the `OUT_DIR` environment variable at build time via `env!("OUT_DIR")`](https://github.com/rust-lang/cargo/issues/3368) . They should instead check the variable at runtime with `std::env`. That the value was set at build time was a bug, and incorrect when cross-compiling. This change is known to cause breakage. * [Add `--all` flag to `cargo test`](https://github.com/rust-lang/cargo/pull/3221) * [Compile statically against the MSVC CRT](https://github.com/rust-lang/cargo/pull/3363) * [Mix feature flags into fingerprint/metadata shorthash](https://github.com/rust-lang/cargo/pull/3102) * [Link OpenSSL statically on OSX](https://github.com/rust-lang/cargo/pull/3311) * [Apply new fingerprinting to build dir outputs](https://github.com/rust-lang/cargo/pull/3310) * [Test for bad path overrides with summaries](https://github.com/rust-lang/cargo/pull/3336) * [Require `cargo install --vers` to take a semver version](https://github.com/rust-lang/cargo/pull/3338) * [Fix retrying crate downloads for network errors](https://github.com/rust-lang/cargo/pull/3348) * [Implement string lookup for `build.rustflags` config key](https://github.com/rust-lang/cargo/pull/3356) * [Emit more info on –message-format=json](https://github.com/rust-lang/cargo/pull/3319) * [Assume `build.rs` in the same directory as `Cargo.toml` is a build script](https://github.com/rust-lang/cargo/pull/3361) * [Don’t ignore errors in workspace manifest](https://github.com/rust-lang/cargo/pull/3409) * [Fix `--message-format JSON` when rustc emits non-JSON warnings](https://github.com/rust-lang/cargo/pull/3410) [§](https://doc.rust-lang.org/stable/releases.html#tooling) Tooling ------------------------------------------------------------------- * [Test runners (binaries built with `--test`) now support a `--list` argument that lists the tests it contains](https://github.com/rust-lang/rust/pull/38185) * [Test runners now support a `--exact` argument that makes the test filter match exactly, instead of matching only a substring of the test name](https://github.com/rust-lang/rust/pull/38181) * [rustdoc supports a `--playground-url` flag](https://github.com/rust-lang/rust/pull/37763) * [rustdoc provides more details about `#[should_panic]` errors](https://github.com/rust-lang/rust/pull/37749) [§](https://doc.rust-lang.org/stable/releases.html#misc-38) Misc ---------------------------------------------------------------- * [The Rust build system is now written in Rust](https://github.com/rust-lang/rust/pull/37817) . The Makefiles may continue to be used in this release by passing `--disable-rustbuild` to the configure script, but they will be deleted soon. Note that the new build system uses a different on-disk layout that will likely affect any scripts building Rust. * [Rust supports i686-unknown-openbsd](https://github.com/rust-lang/rust/pull/38086) . Tier 3 support. No testing or releases. * [Rust supports the MSP430](https://github.com/rust-lang/rust/pull/37627) . Tier 3 support. No testing or releases. * [Rust supports the ARMv5TE architecture](https://github.com/rust-lang/rust/pull/37615) . Tier 3 support. No testing or releases. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-77) Compatibility Notes ---------------------------------------------------------------------------------------------- * [A number of minor changes to name resolution have been activated](https://github.com/rust-lang/rust/pull/37127) . They add up to more consistent semantics, allowing for future evolution of Rust macros. Specified in [RFC 1560](https://github.com/rust-lang/rfcs/blob/master/text/1560-name-resolution.md) , see its section on [“changes”](https://github.com/rust-lang/rfcs/blob/master/text/1560-name-resolution.md#changes-to-name-resolution-rules) for details of what is different. The breaking changes here have been transitioned through the [`legacy_imports`](https://github.com/rust-lang/rust/pull/38271) lint since 1.14, with no known regressions. * [In this release, Cargo build scripts no longer have access to the `OUT_DIR` environment variable at build time via `env!("OUT_DIR")`](https://github.com/rust-lang/cargo/issues/3368) . They should instead check the variable at runtime with `std::env`. That the value was set at build time was a bug, and incorrect when cross-compiling. This change is known to cause breakage. * [Higher-ranked lifetimes are no longer allowed to appear _only_ in associated types](https://github.com/rust-lang/rust/issues/33685) . The [`hr_lifetime_in_assoc_type` lint](https://github.com/rust-lang/rust/issues/33685) has been a warning since 1.10 and is now an error by default. It will become a hard error in the near future. * [The semantics relating modules to file system directories are changing in minor ways](https://github.com/rust-lang/rust/pull/37602) . This is captured in the new `legacy_directory_ownership` lint, which is a warning in this release, and will become a hard error in the future. * [Rust-ABI symbols are no longer exported from cdylibs](https://github.com/rust-lang/rust/pull/38117) * [Once `Peekable` peeks a `None` it will return that `None` without re-querying the underlying iterator](https://github.com/rust-lang/rust/pull/37834) [§](https://doc.rust-lang.org/stable/releases.html#version-1140-2016-12-22) Version 1.14.0 (2016-12-22) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-77) Language ------------------------------------------------------------------------ * [`..` matches multiple tuple fields in enum variants, structs and tuples](https://github.com/rust-lang/rust/pull/36843) . [RFC 1492](https://github.com/rust-lang/rfcs/blob/master/text/1492-dotdot-in-patterns.md) . * [Safe `fn` items can be coerced to `unsafe fn` pointers](https://github.com/rust-lang/rust/pull/37389) * [`use *` and `use ::*` both glob-import from the crate root](https://github.com/rust-lang/rust/pull/37367) * [It’s now possible to call a `Vec>` without explicit dereferencing](https://github.com/rust-lang/rust/pull/36822) [§](https://doc.rust-lang.org/stable/releases.html#compiler-77) Compiler ------------------------------------------------------------------------ * [Mark enums with non-zero discriminant as non-zero](https://github.com/rust-lang/rust/pull/37224) * [Lower-case `static mut` names are linted like other statics and consts](https://github.com/rust-lang/rust/pull/37162) * [Fix ICE on some macros in const integer positions (e.g. `[u8; m!()]`)](https://github.com/rust-lang/rust/pull/36819) * [Improve error message and snippet for “did you mean `x`”](https://github.com/rust-lang/rust/pull/36798) * [Add a panic-strategy field to the target specification](https://github.com/rust-lang/rust/pull/36794) * [Include LLVM version in `--version --verbose`](https://github.com/rust-lang/rust/pull/37200) [§](https://doc.rust-lang.org/stable/releases.html#compile-time-optimizations) Compile-time Optimizations --------------------------------------------------------------------------------------------------------- * [Improve macro expansion performance](https://github.com/rust-lang/rust/pull/37569) * [Shrink `Expr_::ExprInlineAsm`](https://github.com/rust-lang/rust/pull/37445) * [Replace all uses of SHA-256 with BLAKE2b](https://github.com/rust-lang/rust/pull/37439) * [Reduce the number of bytes hashed by `IchHasher`](https://github.com/rust-lang/rust/pull/37427) * [Avoid more allocations when compiling html5ever](https://github.com/rust-lang/rust/pull/37373) * [Use `SmallVector` in `CombineFields::instantiate`](https://github.com/rust-lang/rust/pull/37322) * [Avoid some allocations in the macro parser](https://github.com/rust-lang/rust/pull/37318) * [Use a faster deflate setting](https://github.com/rust-lang/rust/pull/37298) * [Add `ArrayVec` and `AccumulateVec` to reduce heap allocations during interning of slices](https://github.com/rust-lang/rust/pull/37270) * [Optimize `write_metadata`](https://github.com/rust-lang/rust/pull/37267) * [Don’t process obligation forest cycles when stalled](https://github.com/rust-lang/rust/pull/37231) * [Avoid many `CrateConfig` clones](https://github.com/rust-lang/rust/pull/37161) * [Optimize `Substs::super_fold_with`](https://github.com/rust-lang/rust/pull/37108) * [Optimize `ObligationForest`’s `NodeState` handling](https://github.com/rust-lang/rust/pull/36993) * [Speed up `plug_leaks`](https://github.com/rust-lang/rust/pull/36917) [§](https://doc.rust-lang.org/stable/releases.html#libraries-78) Libraries -------------------------------------------------------------------------- * [`println!()`, with no arguments, prints newline](https://github.com/rust-lang/rust/pull/36825) . Previously, an empty string was required to achieve the same. * [`Wrapping` impls standard binary and unary operators, as well as the `Sum` and `Product` iterators](https://github.com/rust-lang/rust/pull/37356) * [Implement `From> for String` and `From> for Vec`](https://github.com/rust-lang/rust/pull/37326) * [Improve `fold` performance for `chain`, `cloned`, `map`, and `VecDeque` iterators](https://github.com/rust-lang/rust/pull/37315) * [Improve `SipHasher` performance on small values](https://github.com/rust-lang/rust/pull/37312) * [Add Iterator trait TrustedLen to enable better FromIterator / Extend](https://github.com/rust-lang/rust/pull/37306) * [Expand `.zip()` specialization to `.map()` and `.cloned()`](https://github.com/rust-lang/rust/pull/37230) * [`ReadDir` implements `Debug`](https://github.com/rust-lang/rust/pull/37221) * [Implement `RefUnwindSafe` for atomic types](https://github.com/rust-lang/rust/pull/37178) * [Specialize `Vec::extend` to `Vec::extend_from_slice`](https://github.com/rust-lang/rust/pull/37094) * [Avoid allocations in `Decoder::read_str`](https://github.com/rust-lang/rust/pull/37064) * [`io::Error` implements `From`](https://github.com/rust-lang/rust/pull/37037) * [Impl `Debug` for raw pointers to unsized data](https://github.com/rust-lang/rust/pull/36880) * [Don’t reuse `HashMap` random seeds](https://github.com/rust-lang/rust/pull/37470) * [The internal memory layout of `HashMap` is more cache-friendly, for significant improvements in some operations](https://github.com/rust-lang/rust/pull/36692) * [`HashMap` uses less memory on 32-bit architectures](https://github.com/rust-lang/rust/pull/36595) * [Impl `Add<{str, Cow}>` for `Cow`](https://github.com/rust-lang/rust/pull/36430) [§](https://doc.rust-lang.org/stable/releases.html#cargo-76) Cargo ------------------------------------------------------------------ * [Expose rustc cfg values to build scripts](https://github.com/rust-lang/cargo/pull/3243) * [Allow cargo to work with read-only `CARGO_HOME`](https://github.com/rust-lang/cargo/pull/3259) * [Fix passing –features when testing multiple packages](https://github.com/rust-lang/cargo/pull/3280) * [Use a single profile set per workspace](https://github.com/rust-lang/cargo/pull/3249) * [Load `replace` sections from lock files](https://github.com/rust-lang/cargo/pull/3220) * [Ignore `panic` configuration for test/bench profiles](https://github.com/rust-lang/cargo/pull/3175) [§](https://doc.rust-lang.org/stable/releases.html#tooling-1) Tooling --------------------------------------------------------------------- * [rustup is the recommended Rust installation method](https://internals.rust-lang.org/t/beta-testing-rustup-rs/3316/204) * This release includes host (rustc) builds for Linux on MIPS, PowerPC, and S390x. These are [tier 2](https://forge.rust-lang.org/platform-support.html) platforms and may have major defects. Follow the instructions on the website to install, or add the targets to an existing installation with `rustup target add`. The new target triples are: * `mips-unknown-linux-gnu` * `mipsel-unknown-linux-gnu` * `mips64-unknown-linux-gnuabi64` * `mips64el-unknown-linux-gnuabi64` * `powerpc-unknown-linux-gnu` * `powerpc64-unknown-linux-gnu` * `powerpc64le-unknown-linux-gnu` * `s390x-unknown-linux-gnu` * This release includes target (std) builds for ARM Linux running MUSL libc. These are [tier 2](https://forge.rust-lang.org/platform-support.html) platforms and may have major defects. Add the following triples to an existing rustup installation with `rustup target add`: * `arm-unknown-linux-musleabi` * `arm-unknown-linux-musleabihf` * `armv7-unknown-linux-musleabihf` * This release includes [experimental support for WebAssembly](https://users.rust-lang.org/t/compiling-to-the-web-with-rust-and-emscripten/7627) , via the `wasm32-unknown-emscripten` target. This target is known to have major defects. Please test, report, and fix. * rustup no longer installs documentation by default. Run `rustup component add rust-docs` to install. * [Fix line stepping in debugger](https://github.com/rust-lang/rust/pull/37310) * [Enable line number debuginfo in releases](https://github.com/rust-lang/rust/pull/37280) [§](https://doc.rust-lang.org/stable/releases.html#misc-39) Misc ---------------------------------------------------------------- * [Disable jemalloc on aarch64/powerpc/mips](https://github.com/rust-lang/rust/pull/37392) * [Add support for Fuchsia OS](https://github.com/rust-lang/rust/pull/37313) * [Detect local-rebuild by only MAJOR.MINOR version](https://github.com/rust-lang/rust/pull/37273) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-78) Compatibility Notes ---------------------------------------------------------------------------------------------- * [A number of forward-compatibility lints used by the compiler to gradually introduce language changes have been converted to deny by default](https://github.com/rust-lang/rust/pull/36894) : * [“use of inaccessible extern crate erroneously allowed”](https://github.com/rust-lang/rust/issues/36886) * [“type parameter default erroneously allowed in invalid location”](https://github.com/rust-lang/rust/issues/36887) * [“detects super or self keywords at the beginning of global path”](https://github.com/rust-lang/rust/issues/36888) * [“two overlapping inherent impls define an item with the same name were erroneously allowed”](https://github.com/rust-lang/rust/issues/36889) * [“floating-point constants cannot be used in patterns”](https://github.com/rust-lang/rust/issues/36890) * [“constants of struct or enum type can only be used in a pattern if the struct or enum has `#[derive(PartialEq, Eq)]`”](https://github.com/rust-lang/rust/issues/36891) * [“lifetimes or labels named `'_` were erroneously allowed”](https://github.com/rust-lang/rust/issues/36892) * [Prohibit patterns in trait methods without bodies](https://github.com/rust-lang/rust/pull/37378) * [The atomic `Ordering` enum may not be matched exhaustively](https://github.com/rust-lang/rust/pull/37351) * [Future-proofing `#[no_link]` breaks some obscure cases](https://github.com/rust-lang/rust/pull/37247) * [The `$crate` macro variable is accepted in fewer locations](https://github.com/rust-lang/rust/pull/37213) * [Impls specifying extra region requirements beyond the trait they implement are rejected](https://github.com/rust-lang/rust/pull/37167) * [Enums may not be unsized](https://github.com/rust-lang/rust/pull/37111) . Unsized enums are intended to work but never have. For now they are forbidden. * [Enforce the shadowing restrictions from RFC 1560 for today’s macros](https://github.com/rust-lang/rust/pull/36767) [§](https://doc.rust-lang.org/stable/releases.html#version-1130-2016-11-10) Version 1.13.0 (2016-11-10) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-78) Language ------------------------------------------------------------------------ * [Stabilize the `?` operator](https://github.com/rust-lang/rust/pull/36995) . `?` is a simple way to propagate errors, like the `try!` macro, described in [RFC 0243](https://github.com/rust-lang/rfcs/blob/master/text/0243-trait-based-exception-handling.md) . * [Stabilize macros in type position](https://github.com/rust-lang/rust/pull/36014) . Described in [RFC 873](https://github.com/rust-lang/rfcs/blob/master/text/0873-type-macros.md) . * [Stabilize attributes on statements](https://github.com/rust-lang/rust/pull/36995) . Described in [RFC 0016](https://github.com/rust-lang/rfcs/blob/master/text/0016-more-attributes.md) . * [Fix `#[derive]` for empty tuple structs/variants](https://github.com/rust-lang/rust/pull/35728) * [Fix lifetime rules for ‘if’ conditions](https://github.com/rust-lang/rust/pull/36029) * [Avoid loading and parsing unconfigured non-inline modules](https://github.com/rust-lang/rust/pull/36482) [§](https://doc.rust-lang.org/stable/releases.html#compiler-78) Compiler ------------------------------------------------------------------------ * [Add the `-C link-arg` argument](https://github.com/rust-lang/rust/pull/36574) * [Remove the old AST-based backend from rustc\_trans](https://github.com/rust-lang/rust/pull/35764) * [Don’t enable NEON by default on armv7 Linux](https://github.com/rust-lang/rust/pull/35814) * [Fix debug line number info for macro expansions](https://github.com/rust-lang/rust/pull/35238) * [Do not emit “class method” debuginfo for types that are not DICompositeType](https://github.com/rust-lang/rust/pull/36008) * [Warn about multiple conflicting #\[repr\] hints](https://github.com/rust-lang/rust/pull/34623) * [When sizing DST, don’t double-count nested struct prefixes](https://github.com/rust-lang/rust/pull/36351) * [Default RUST\_MIN\_STACK to 16MiB for now](https://github.com/rust-lang/rust/pull/36505) * [Improve rlib metadata format](https://github.com/rust-lang/rust/pull/36551) . Reduces rlib size significantly. * [Reject macros with empty repetitions to avoid infinite loop](https://github.com/rust-lang/rust/pull/36721) * [Expand macros without recursing to avoid stack overflows](https://github.com/rust-lang/rust/pull/36214) [§](https://doc.rust-lang.org/stable/releases.html#diagnostics) Diagnostics --------------------------------------------------------------------------- * [Replace macro backtraces with labeled local uses](https://github.com/rust-lang/rust/pull/35702) * [Improve error message for misplaced doc comments](https://github.com/rust-lang/rust/pull/33922) * [Buffer unix and lock windows to prevent message interleaving](https://github.com/rust-lang/rust/pull/35975) * [Update lifetime errors to specifically note temporaries](https://github.com/rust-lang/rust/pull/36171) * [Special case a few colors for Windows](https://github.com/rust-lang/rust/pull/36178) * [Suggest `use self` when such an import resolves](https://github.com/rust-lang/rust/pull/36289) * [Be more specific when type parameter shadows primitive type](https://github.com/rust-lang/rust/pull/36338) * Many minor improvements [§](https://doc.rust-lang.org/stable/releases.html#compile-time-optimizations-1) Compile-time Optimizations ----------------------------------------------------------------------------------------------------------- * [Compute and cache HIR hashes at beginning](https://github.com/rust-lang/rust/pull/35854) * [Don’t hash types in loan paths](https://github.com/rust-lang/rust/pull/36004) * [Cache projections in trans](https://github.com/rust-lang/rust/pull/35761) * [Optimize the parser’s last token handling](https://github.com/rust-lang/rust/pull/36527) * [Only instantiate #\[inline\] functions in codegen units referencing them](https://github.com/rust-lang/rust/pull/36524) . This leads to big improvements in cases where crates export define many inline functions without using them directly. * [Lazily allocate TypedArena’s first chunk](https://github.com/rust-lang/rust/pull/36592) * [Don’t allocate during default HashSet creation](https://github.com/rust-lang/rust/pull/36734) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-73) Stabilized APIs -------------------------------------------------------------------------------------- * [`checked_abs`](https://doc.rust-lang.org/std/primitive.i32.html#method.checked_abs) * [`wrapping_abs`](https://doc.rust-lang.org/std/primitive.i32.html#method.wrapping_abs) * [`overflowing_abs`](https://doc.rust-lang.org/std/primitive.i32.html#method.overflowing_abs) * [`RefCell::try_borrow`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.try_borrow) * [`RefCell::try_borrow_mut`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.try_borrow_mut) [§](https://doc.rust-lang.org/stable/releases.html#libraries-79) Libraries -------------------------------------------------------------------------- * [Add `assert_ne!` and `debug_assert_ne!`](https://github.com/rust-lang/rust/pull/35074) * [Make `vec_deque::Drain`, `hash_map::Drain`, and `hash_set::Drain` covariant](https://github.com/rust-lang/rust/pull/35354) * [Implement `AsRef<[T]>` for `std::slice::Iter`](https://github.com/rust-lang/rust/pull/35559) * [Implement `Debug` for `std::vec::IntoIter`](https://github.com/rust-lang/rust/pull/35707) * [`CString`: avoid excessive growth just to 0-terminate](https://github.com/rust-lang/rust/pull/35871) * [Implement `CoerceUnsized` for `{Cell, RefCell, UnsafeCell}`](https://github.com/rust-lang/rust/pull/35627) * [Use arc4rand on FreeBSD](https://github.com/rust-lang/rust/pull/35884) * [memrchr: Correct aligned offset computation](https://github.com/rust-lang/rust/pull/35969) * [Improve Demangling of Rust Symbols](https://github.com/rust-lang/rust/pull/36059) * [Use monotonic time in condition variables](https://github.com/rust-lang/rust/pull/35048) * [Implement `Debug` for `std::path::{Components,Iter}`](https://github.com/rust-lang/rust/pull/36101) * [Implement conversion traits for `char`](https://github.com/rust-lang/rust/pull/35755) * [Fix illegal instruction caused by overflow in channel cloning](https://github.com/rust-lang/rust/pull/36104) * [Zero first byte of CString on drop](https://github.com/rust-lang/rust/pull/36264) * [Inherit overflow checks for sum and product](https://github.com/rust-lang/rust/pull/36372) * [Add missing Eq implementations](https://github.com/rust-lang/rust/pull/36423) * [Implement `Debug` for `DirEntry`](https://github.com/rust-lang/rust/pull/36631) * [When `getaddrinfo` returns `EAI_SYSTEM` retrieve actual error from `errno`](https://github.com/rust-lang/rust/pull/36754) * [`SipHasher`](https://doc.rust-lang.org/std/hash/struct.SipHasher.html) is deprecated. Use [`DefaultHasher`](https://doc.rust-lang.org/std/collections/hash_map/struct.DefaultHasher.html) . * [Implement more traits for `std::io::ErrorKind`](https://github.com/rust-lang/rust/pull/35911) * [Optimize BinaryHeap bounds checking](https://github.com/rust-lang/rust/pull/36072) * [Work around pointer aliasing issue in `Vec::extend_from_slice`, `extend_with_element`](https://github.com/rust-lang/rust/pull/36355) * [Fix overflow checking in unsigned pow()](https://github.com/rust-lang/rust/pull/34942) [§](https://doc.rust-lang.org/stable/releases.html#cargo-77) Cargo ------------------------------------------------------------------ * This release includes security fixes to both curl and OpenSSL. * [Fix transitive doctests when panic=abort](https://github.com/rust-lang/cargo/pull/3021) * [Add –all-features flag to cargo](https://github.com/rust-lang/cargo/pull/3038) * [Reject path-based dependencies in `cargo package`](https://github.com/rust-lang/cargo/pull/3060) * [Don’t parse the home directory more than once](https://github.com/rust-lang/cargo/pull/3078) * [Don’t try to generate Cargo.lock on empty workspaces](https://github.com/rust-lang/cargo/pull/3092) * [Update OpenSSL to 1.0.2j](https://github.com/rust-lang/cargo/pull/3121) * [Add license and license\_file to cargo metadata output](https://github.com/rust-lang/cargo/pull/3110) * [Make crates-io registry URL optional in config; ignore all changes to source.crates-io](https://github.com/rust-lang/cargo/pull/3089) * [Don’t download dependencies from other platforms](https://github.com/rust-lang/cargo/pull/3123) * [Build transitive dev-dependencies when needed](https://github.com/rust-lang/cargo/pull/3125) * [Add support for per-target rustflags in .cargo/config](https://github.com/rust-lang/cargo/pull/3157) * [Avoid updating registry when adding existing deps](https://github.com/rust-lang/cargo/pull/3144) * [Warn about path overrides that won’t work](https://github.com/rust-lang/cargo/pull/3136) * [Use workspaces during `cargo install`](https://github.com/rust-lang/cargo/pull/3146) * [Leak mspdbsrv.exe processes on Windows](https://github.com/rust-lang/cargo/pull/3162) * [Add –message-format flag](https://github.com/rust-lang/cargo/pull/3000) * [Pass target environment for rustdoc](https://github.com/rust-lang/cargo/pull/3205) * [Use `CommandExt::exec` for `cargo run` on Unix](https://github.com/rust-lang/cargo/pull/2818) * [Update curl and curl-sys](https://github.com/rust-lang/cargo/pull/3241) * [Call rustdoc test with the correct cfg flags of a package](https://github.com/rust-lang/cargo/pull/3242) [§](https://doc.rust-lang.org/stable/releases.html#tooling-2) Tooling --------------------------------------------------------------------- * [rustdoc: Add the `--sysroot` argument](https://github.com/rust-lang/rust/pull/36586) * [rustdoc: Fix a couple of issues with the search results](https://github.com/rust-lang/rust/pull/35655) * [rustdoc: remove the `!` from macro URLs and titles](https://github.com/rust-lang/rust/pull/35234) * [gdb: Fix pretty-printing special-cased Rust types](https://github.com/rust-lang/rust/pull/35585) * [rustdoc: Filter more incorrect methods inherited through Deref](https://github.com/rust-lang/rust/pull/36266) [§](https://doc.rust-lang.org/stable/releases.html#misc-40) Misc ---------------------------------------------------------------- * [Remove unmaintained style guide](https://github.com/rust-lang/rust/pull/35124) * [Add s390x support](https://github.com/rust-lang/rust/pull/36369) * [Initial work at Haiku OS support](https://github.com/rust-lang/rust/pull/36727) * [Add mips-uclibc targets](https://github.com/rust-lang/rust/pull/35734) * [Crate-ify compiler-rt into compiler-builtins](https://github.com/rust-lang/rust/pull/35021) * [Add rustc version info (git hash + date) to dist tarball](https://github.com/rust-lang/rust/pull/36213) * Many documentation improvements [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-79) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`SipHasher`](https://doc.rust-lang.org/std/hash/struct.SipHasher.html) is deprecated. Use [`DefaultHasher`](https://doc.rust-lang.org/std/collections/hash_map/struct.DefaultHasher.html) . * [Deny (by default) transmuting from fn item types to pointer-sized types](https://github.com/rust-lang/rust/pull/34923) . Continuing the long transition to zero-sized fn items, per [RFC 401](https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md) . * [Fix `#[derive]` for empty tuple structs/variants](https://github.com/rust-lang/rust/pull/35728) . Part of [RFC 1506](https://github.com/rust-lang/rfcs/pull/1506) . * [Issue deprecation warnings for safe accesses to extern statics](https://github.com/rust-lang/rust/pull/36173) * [Fix lifetime rules for ‘if’ conditions](https://github.com/rust-lang/rust/pull/36029) . * [Inherit overflow checks for sum and product](https://github.com/rust-lang/rust/pull/36372) . * [Forbid user-defined macros named “macro\_rules”](https://github.com/rust-lang/rust/pull/36730) . [§](https://doc.rust-lang.org/stable/releases.html#version-1121-2016-10-20) Version 1.12.1 (2016-10-20) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#regression-fixes) Regression Fixes ------------------------------------------------------------------------------------- * [ICE: ‘rustc’ panicked at ‘assertion failed: concrete\_substs.is\_normalized\_for\_trans()’ #36381](https://github.com/rust-lang/rust/issues/36381) * [Confusion with double negation and booleans](https://github.com/rust-lang/rust/issues/36856) * [rustc 1.12.0 fails with SIGSEGV in release mode (syn crate 0.8.0)](https://github.com/rust-lang/rust/issues/36875) * [Rustc 1.12.0 Windows build of `ethcore` crate fails with LLVM error](https://github.com/rust-lang/rust/issues/36924) * [1.12.0: High memory usage when linking in release mode with debug info](https://github.com/rust-lang/rust/issues/36926) * [Corrupted memory after updated to 1.12](https://github.com/rust-lang/rust/issues/36936) * [“Let NullaryConstructor = something;” causes internal compiler error: “tried to overwrite interned AdtDef”](https://github.com/rust-lang/rust/issues/37026) * [Fix ICE: inject bitcast if types mismatch for invokes/calls/stores](https://github.com/rust-lang/rust/issues/37112) * [debuginfo: Handle spread\_arg case in MIR-trans in a more stable way.](https://github.com/rust-lang/rust/issues/37153) [§](https://doc.rust-lang.org/stable/releases.html#version-1120-2016-09-29) Version 1.12.0 (2016-09-29) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#highlights) Highlights ------------------------------------------------------------------------- * [`rustc` translates code to LLVM IR via its own “middle” IR (MIR)](https://github.com/rust-lang/rust/pull/34096) . This translation pass is far simpler than the previous AST->LLVM pass, and creates opportunities to perform new optimizations directly on the MIR. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/04/19/MIR.html) . * [`rustc` presents a new, more readable error format, along with machine-readable JSON error output for use by IDEs](https://github.com/rust-lang/rust/pull/35401) . Most common editors supporting Rust have been updated to work with it. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html) . [§](https://doc.rust-lang.org/stable/releases.html#compiler-79) Compiler ------------------------------------------------------------------------ * [`rustc` translates code to LLVM IR via its own “middle” IR (MIR)](https://github.com/rust-lang/rust/pull/34096) . This translation pass is far simpler than the previous AST->LLVM pass, and creates opportunities to perform new optimizations directly on the MIR. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/04/19/MIR.html) . * [Print the Rust target name, not the LLVM target name, with `--print target-list`](https://github.com/rust-lang/rust/pull/35489) * [The computation of `TypeId` is correct in some cases where it was previously producing inconsistent results](https://github.com/rust-lang/rust/pull/35267) * [The `mips-unknown-linux-gnu` target uses hardware floating point by default](https://github.com/rust-lang/rust/pull/34910) * [The `rustc` arguments, `--print target-cpus`, `--print target-features`, `--print relocation-models`, and `--print code-models` print the available options to the `-C target-cpu`, `-C target-feature`, `-C relocation-model` and `-C code-model` code generation arguments](https://github.com/rust-lang/rust/pull/34845) * [`rustc` supports three new MUSL targets on ARM: `arm-unknown-linux-musleabi`, `arm-unknown-linux-musleabihf`, and `armv7-unknown-linux-musleabihf`](https://github.com/rust-lang/rust/pull/35060) . These targets produce statically-linked binaries. There are no binary release builds yet though. [§](https://doc.rust-lang.org/stable/releases.html#diagnostics-1) Diagnostics ----------------------------------------------------------------------------- * [`rustc` presents a new, more readable error format, along with machine-readable JSON error output for use by IDEs](https://github.com/rust-lang/rust/pull/35401) . Most common editors supporting Rust have been updated to work with it. It was previously described [on the Rust blog](https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html) . * [In error descriptions, references are now described in plain English, instead of as “&-ptr”](https://github.com/rust-lang/rust/pull/35611) * [In error type descriptions, unknown numeric types are named `{integer}` or `{float}` instead of `_`](https://github.com/rust-lang/rust/pull/35080) * [`rustc` emits a clearer error when inner attributes follow a doc comment](https://github.com/rust-lang/rust/pull/34676) [§](https://doc.rust-lang.org/stable/releases.html#language-79) Language ------------------------------------------------------------------------ * [`macro_rules!` invocations can be made within `macro_rules!` invocations](https://github.com/rust-lang/rust/pull/34925) * [`macro_rules!` meta-variables are hygienic](https://github.com/rust-lang/rust/pull/35453) * [`macro_rules!` `tt` matchers can be reparsed correctly, making them much more useful](https://github.com/rust-lang/rust/pull/34908) * [`macro_rules!` `stmt` matchers correctly consume the entire contents when inside non-braces invocations](https://github.com/rust-lang/rust/pull/34886) * [Semicolons are properly required as statement delimiters inside `macro_rules!` invocations](https://github.com/rust-lang/rust/pull/34660) * [`cfg_attr` works on `path` attributes](https://github.com/rust-lang/rust/pull/34546) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-74) Stabilized APIs -------------------------------------------------------------------------------------- * [`Cell::as_ptr`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.as_ptr) * [`RefCell::as_ptr`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.as_ptr) * [`IpAddr::is_unspecified`](https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_unspecified) * [`IpAddr::is_loopback`](https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_loopback) * [`IpAddr::is_multicast`](https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_multicast) * [`Ipv4Addr::is_unspecified`](https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html#method.is_unspecified) * [`Ipv6Addr::octets`](https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html#method.octets) * [`LinkedList::contains`](https://doc.rust-lang.org/std/collections/linked_list/struct.LinkedList.html#method.contains) * [`VecDeque::contains`](https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html#method.contains) * [`ExitStatusExt::from_raw`](https://doc.rust-lang.org/std/os/unix/process/trait.ExitStatusExt.html#tymethod.from_raw) . Both on Unix and Windows. * [`Receiver::recv_timeout`](https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.recv_timeout) * [`RecvTimeoutError`](https://doc.rust-lang.org/std/sync/mpsc/enum.RecvTimeoutError.html) * [`BinaryHeap::peek_mut`](https://doc.rust-lang.org/std/collections/binary_heap/struct.BinaryHeap.html#method.peek_mut) * [`PeekMut`](https://doc.rust-lang.org/std/collections/binary_heap/struct.PeekMut.html) * [`iter::Product`](https://doc.rust-lang.org/std/iter/trait.Product.html) * [`iter::Sum`](https://doc.rust-lang.org/std/iter/trait.Sum.html) * [`OccupiedEntry::remove_entry`](https://doc.rust-lang.org/std/collections/btree_map/struct.OccupiedEntry.html#method.remove_entry) * [`VacantEntry::into_key`](https://doc.rust-lang.org/std/collections/btree_map/struct.VacantEntry.html#method.into_key) [§](https://doc.rust-lang.org/stable/releases.html#libraries-80) Libraries -------------------------------------------------------------------------- * [The `format!` macro and friends now allow a single argument to be formatted in multiple styles](https://github.com/rust-lang/rust/pull/33642) * [The lifetime bounds on `[T]::binary_search_by` and `[T]::binary_search_by_key` have been adjusted to be more flexible](https://github.com/rust-lang/rust/pull/34762) * [`Option` implements `From` for its contained type](https://github.com/rust-lang/rust/pull/34828) * [`Cell`, `RefCell` and `UnsafeCell` implement `From` for their contained type](https://github.com/rust-lang/rust/pull/35392) * [`RwLock` panics if the reader count overflows](https://github.com/rust-lang/rust/pull/35378) * [`vec_deque::Drain`, `hash_map::Drain` and `hash_set::Drain` are covariant](https://github.com/rust-lang/rust/pull/35354) * [`vec::Drain` and `binary_heap::Drain` are covariant](https://github.com/rust-lang/rust/pull/34951) * [`Cow` implements `FromIterator` for `char`, `&str` and `String`](https://github.com/rust-lang/rust/pull/35064) * [Sockets on Linux are correctly closed in subprocesses via `SOCK_CLOEXEC`](https://github.com/rust-lang/rust/pull/34946) * [`hash_map::Entry`, `hash_map::VacantEntry` and `hash_map::OccupiedEntry` implement `Debug`](https://github.com/rust-lang/rust/pull/34937) * [`btree_map::Entry`, `btree_map::VacantEntry` and `btree_map::OccupiedEntry` implement `Debug`](https://github.com/rust-lang/rust/pull/34885) * [`String` implements `AddAssign`](https://github.com/rust-lang/rust/pull/34890) * [Variadic `extern fn` pointers implement the `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`, `fmt::Pointer`, and `fmt::Debug` traits](https://github.com/rust-lang/rust/pull/34879) * [`FileType` implements `Debug`](https://github.com/rust-lang/rust/pull/34757) * [References to `Mutex` and `RwLock` are unwind-safe](https://github.com/rust-lang/rust/pull/34756) * [`mpsc::sync_channel` `Receiver`s return any available message before reporting a disconnect](https://github.com/rust-lang/rust/pull/34731) * [Unicode definitions have been updated to 9.0](https://github.com/rust-lang/rust/pull/34599) * [`env` iterators implement `DoubleEndedIterator`](https://github.com/rust-lang/rust/pull/33312) [§](https://doc.rust-lang.org/stable/releases.html#cargo-78) Cargo ------------------------------------------------------------------ * [Support local mirrors of registries](https://github.com/rust-lang/cargo/pull/2857) * [Add support for command aliases](https://github.com/rust-lang/cargo/pull/2679) * [Allow `opt-level="s"` / `opt-level="z"` in profile overrides](https://github.com/rust-lang/cargo/pull/3007) * [Make `cargo doc --open --target` work as expected](https://github.com/rust-lang/cargo/pull/2988) * [Speed up noop registry updates](https://github.com/rust-lang/cargo/pull/2974) * [Update OpenSSL](https://github.com/rust-lang/cargo/pull/2971) * [Fix `--panic=abort` with plugins](https://github.com/rust-lang/cargo/pull/2954) * [Always pass `-C metadata` to the compiler](https://github.com/rust-lang/cargo/pull/2946) * [Fix depending on git repos with workspaces](https://github.com/rust-lang/cargo/pull/2938) * [Add a `--lib` flag to `cargo new`](https://github.com/rust-lang/cargo/pull/2921) * [Add `http.cainfo` for custom certs](https://github.com/rust-lang/cargo/pull/2917) * [Indicate the compilation profile after compiling](https://github.com/rust-lang/cargo/pull/2909) * [Allow enabling features for dependencies with `--features`](https://github.com/rust-lang/cargo/pull/2876) * [Add `--jobs` flag to `cargo package`](https://github.com/rust-lang/cargo/pull/2867) * [Add `--dry-run` to `cargo publish`](https://github.com/rust-lang/cargo/pull/2849) * [Add support for `RUSTDOCFLAGS`](https://github.com/rust-lang/cargo/pull/2794) [§](https://doc.rust-lang.org/stable/releases.html#performance) Performance --------------------------------------------------------------------------- * [`panic::catch_unwind` is more optimized](https://github.com/rust-lang/rust/pull/35444) * [`panic::catch_unwind` no longer accesses thread-local storage on entry](https://github.com/rust-lang/rust/pull/34866) [§](https://doc.rust-lang.org/stable/releases.html#tooling-3) Tooling --------------------------------------------------------------------- * [Test binaries now support a `--test-threads` argument to specify the number of threads used to run tests, and which acts the same as the `RUST_TEST_THREADS` environment variable](https://github.com/rust-lang/rust/pull/35414) * [The test runner now emits a warning when tests run over 60 seconds](https://github.com/rust-lang/rust/pull/35405) * [rustdoc: Fix methods in search results](https://github.com/rust-lang/rust/pull/34752) * [`rust-lldb` warns about unsupported versions of LLDB](https://github.com/rust-lang/rust/pull/34646) * [Rust releases now come with source packages that can be installed by rustup via `rustup component add rust-src`](https://github.com/rust-lang/rust/pull/34366) . The resulting source code can be used by tools and IDES, located in the sysroot under `lib/rustlib/src`. [§](https://doc.rust-lang.org/stable/releases.html#misc-41) Misc ---------------------------------------------------------------- * [The compiler can now be built against LLVM 3.9](https://github.com/rust-lang/rust/pull/35594) * Many minor improvements to the documentation. * [The Rust exception handling “personality” routine is now written in Rust](https://github.com/rust-lang/rust/pull/34832) [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-80) Compatibility Notes ---------------------------------------------------------------------------------------------- * [When printing Windows `OsStr`s, unpaired surrogate codepoints are escaped with the lowercase format instead of the uppercase](https://github.com/rust-lang/rust/pull/35084) * [When formatting strings, if “precision” is specified, the “fill”, “align” and “width” specifiers are no longer ignored](https://github.com/rust-lang/rust/pull/34544) * [The `Debug` impl for strings no longer escapes all non-ASCII characters](https://github.com/rust-lang/rust/pull/34485) [§](https://doc.rust-lang.org/stable/releases.html#version-1110-2016-08-18) Version 1.11.0 (2016-08-18) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-80) Language ------------------------------------------------------------------------ * [Support nested `cfg_attr` attributes](https://github.com/rust-lang/rust/pull/34216) * [Allow statement-generating braced macro invocations at the end of blocks](https://github.com/rust-lang/rust/pull/34436) * [Macros can be expanded inside of trait definitions](https://github.com/rust-lang/rust/pull/34213) * [`#[macro_use]` works properly when it is itself expanded from a macro](https://github.com/rust-lang/rust/pull/34032) [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-75) Stabilized APIs -------------------------------------------------------------------------------------- * [`BinaryHeap::append`](https://doc.rust-lang.org/std/collections/binary_heap/struct.BinaryHeap.html#method.append) * [`BTreeMap::append`](https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.append) * [`BTreeMap::split_off`](https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html#method.split_off) * [`BTreeSet::append`](https://doc.rust-lang.org/std/collections/btree_set/struct.BTreeSet.html#method.append) * [`BTreeSet::split_off`](https://doc.rust-lang.org/std/collections/btree_set/struct.BTreeSet.html#method.split_off) * [`f32::to_degrees`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_degrees) (in libcore - previously stabilized in libstd) * [`f32::to_radians`](https://doc.rust-lang.org/std/primitive.f32.html#method.to_radians) (in libcore - previously stabilized in libstd) * [`f64::to_degrees`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_degrees) (in libcore - previously stabilized in libstd) * [`f64::to_radians`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_radians) (in libcore - previously stabilized in libstd) * [`Iterator::sum`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum) * [`Iterator::product`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.product) * [`Cell::get_mut`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get_mut) * [`RefCell::get_mut`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.get_mut) [§](https://doc.rust-lang.org/stable/releases.html#libraries-81) Libraries -------------------------------------------------------------------------- * [The `thread_local!` macro supports multiple definitions in a single invocation, and can apply attributes](https://github.com/rust-lang/rust/pull/34077) * [`Cow` implements `Default`](https://github.com/rust-lang/rust/pull/34305) * [`Wrapping` implements binary, octal, lower-hex and upper-hex `Display` formatting](https://github.com/rust-lang/rust/pull/34190) * [The range types implement `Hash`](https://github.com/rust-lang/rust/pull/34180) * [`lookup_host` ignores unknown address types](https://github.com/rust-lang/rust/pull/34067) * [`assert_eq!` accepts a custom error message, like `assert!` does](https://github.com/rust-lang/rust/pull/33976) * [The main thread is now called “main” instead of “
”](https://github.com/rust-lang/rust/pull/33803) [§](https://doc.rust-lang.org/stable/releases.html#cargo-79) Cargo ------------------------------------------------------------------ * [Disallow specifying features of transitive deps](https://github.com/rust-lang/cargo/pull/2821) * [Add color support for Windows consoles](https://github.com/rust-lang/cargo/pull/2804) * [Fix `harness = false` on `[lib]` sections](https://github.com/rust-lang/cargo/pull/2795) * [Don’t panic when `links` contains a ‘.’](https://github.com/rust-lang/cargo/pull/2787) * [Build scripts can emit warnings](https://github.com/rust-lang/cargo/pull/2630) , and `-vv` prints warnings for all crates. * [Ignore file locks on OS X NFS mounts](https://github.com/rust-lang/cargo/pull/2720) * [Don’t warn about `package.metadata` keys](https://github.com/rust-lang/cargo/pull/2668) . This provides room for expansion by arbitrary tools. * [Add support for cdylib crate types](https://github.com/rust-lang/cargo/pull/2741) * [Prevent publishing crates when files are dirty](https://github.com/rust-lang/cargo/pull/2781) * [Don’t fetch all crates on clean](https://github.com/rust-lang/cargo/pull/2704) * [Propagate –color option to rustc](https://github.com/rust-lang/cargo/pull/2779) * [Fix `cargo doc --open` on Windows](https://github.com/rust-lang/cargo/pull/2780) * [Improve autocompletion](https://github.com/rust-lang/cargo/pull/2772) * [Configure colors of stderr as well as stdout](https://github.com/rust-lang/cargo/pull/2739) [§](https://doc.rust-lang.org/stable/releases.html#performance-1) Performance ----------------------------------------------------------------------------- * [Caching projections speeds up type check dramatically for some workloads](https://github.com/rust-lang/rust/pull/33816) * [The default `HashMap` hasher is SipHash 1-3 instead of SipHash 2-4](https://github.com/rust-lang/rust/pull/33940) This hasher is faster, but is believed to provide sufficient protection from collision attacks. * [Comparison of `Ipv4Addr` is 10x faster](https://github.com/rust-lang/rust/pull/33891) [§](https://doc.rust-lang.org/stable/releases.html#rustdoc-26) Rustdoc ---------------------------------------------------------------------- * [Fix empty implementation section on some module pages](https://github.com/rust-lang/rust/pull/34536) * [Fix inlined renamed re-exports in import lists](https://github.com/rust-lang/rust/pull/34479) * [Fix search result layout for enum variants and struct fields](https://github.com/rust-lang/rust/pull/34477) * [Fix issues with source links to external crates](https://github.com/rust-lang/rust/pull/34387) * [Fix redirect pages for renamed re-exports](https://github.com/rust-lang/rust/pull/34245) [§](https://doc.rust-lang.org/stable/releases.html#tooling-4) Tooling --------------------------------------------------------------------- * [rustc is better at finding the MSVC toolchain](https://github.com/rust-lang/rust/pull/34492) * [When emitting debug info, rustc emits frame pointers for closures, shims and glue, as it does for all other functions](https://github.com/rust-lang/rust/pull/33909) * [rust-lldb warns about unsupported versions of LLDB](https://github.com/rust-lang/rust/pull/34646) * Many more errors have been given error codes and extended explanations * API documentation continues to be improved, with many new examples [§](https://doc.rust-lang.org/stable/releases.html#misc-42) Misc ---------------------------------------------------------------- * [rustc no longer hangs when dependencies recursively re-export submodules](https://github.com/rust-lang/rust/pull/34542) * [rustc requires LLVM 3.7+](https://github.com/rust-lang/rust/pull/34104) * [The ‘How Safe and Unsafe Interact’ chapter of The Rustonomicon was rewritten](https://github.com/rust-lang/rust/pull/33895) * [rustc support 16-bit pointer sizes](https://github.com/rust-lang/rust/pull/33460) . No targets use this yet, but it works toward AVR support. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-81) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`const`s and `static`s may not have unsized types](https://github.com/rust-lang/rust/pull/34443) * [The new follow-set rules that place restrictions on `macro_rules!` in order to ensure syntax forward-compatibility have been enabled](https://github.com/rust-lang/rust/pull/33982) This was an [amendment to RFC 550](https://github.com/rust-lang/rfcs/pull/1384) , and has been a warning since 1.10. * [`cfg` attribute process has been refactored to fix various bugs](https://github.com/rust-lang/rust/pull/33706) . This causes breakage in some corner cases. [§](https://doc.rust-lang.org/stable/releases.html#version-1100-2016-07-07) Version 1.10.0 (2016-07-07) ======================================================================================================= [§](https://doc.rust-lang.org/stable/releases.html#language-81) Language ------------------------------------------------------------------------ * [`Copy` types are required to have a trivial implementation of `Clone`](https://github.com/rust-lang/rust/pull/33420) . [RFC 1521](https://github.com/rust-lang/rfcs/blob/master/text/1521-copy-clone-semantics.md) . * [Single-variant enums support the `#[repr(..)]` attribute](https://github.com/rust-lang/rust/pull/33355) . * [Fix `#[derive(RustcEncodable)]` in the presence of other `encode` methods](https://github.com/rust-lang/rust/pull/32908) . * [`panic!` can be converted to a runtime abort with the `-C panic=abort` flag](https://github.com/rust-lang/rust/pull/32900) . [RFC 1513](https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md) . * [Add a new crate type, ‘cdylib’](https://github.com/rust-lang/rust/pull/33553) . cdylibs are dynamic libraries suitable for loading by non-Rust hosts. [RFC 1510](https://github.com/rust-lang/rfcs/blob/master/text/1510-cdylib.md) . Note that Cargo does not yet directly support cdylibs. [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-76) Stabilized APIs -------------------------------------------------------------------------------------- * `os::windows::fs::OpenOptionsExt::access_mode` * `os::windows::fs::OpenOptionsExt::share_mode` * `os::windows::fs::OpenOptionsExt::custom_flags` * `os::windows::fs::OpenOptionsExt::attributes` * `os::windows::fs::OpenOptionsExt::security_qos_flags` * `os::unix::fs::OpenOptionsExt::custom_flags` * [`sync::Weak::new`](http://doc.rust-lang.org/alloc/arc/struct.Weak.html#method.new) * `Default for sync::Weak` * [`panic::set_hook`](http://doc.rust-lang.org/std/panic/fn.set_hook.html) * [`panic::take_hook`](http://doc.rust-lang.org/std/panic/fn.take_hook.html) * [`panic::PanicInfo`](http://doc.rust-lang.org/std/panic/struct.PanicInfo.html) * [`panic::PanicInfo::payload`](http://doc.rust-lang.org/std/panic/struct.PanicInfo.html#method.payload) * [`panic::PanicInfo::location`](http://doc.rust-lang.org/std/panic/struct.PanicInfo.html#method.location) * [`panic::Location`](http://doc.rust-lang.org/std/panic/struct.Location.html) * [`panic::Location::file`](http://doc.rust-lang.org/std/panic/struct.Location.html#method.file) * [`panic::Location::line`](http://doc.rust-lang.org/std/panic/struct.Location.html#method.line) * [`ffi::CStr::from_bytes_with_nul`](http://doc.rust-lang.org/std/ffi/struct.CStr.html#method.from_bytes_with_nul) * [`ffi::CStr::from_bytes_with_nul_unchecked`](http://doc.rust-lang.org/std/ffi/struct.CStr.html#method.from_bytes_with_nul_unchecked) * [`ffi::FromBytesWithNulError`](http://doc.rust-lang.org/std/ffi/struct.FromBytesWithNulError.html) * [`fs::Metadata::modified`](http://doc.rust-lang.org/std/fs/struct.Metadata.html#method.modified) * [`fs::Metadata::accessed`](http://doc.rust-lang.org/std/fs/struct.Metadata.html#method.accessed) * [`fs::Metadata::created`](http://doc.rust-lang.org/std/fs/struct.Metadata.html#method.created) * `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange` * `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak` * `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key` * `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}` * [`SocketAddr::is_unnamed`](http://doc.rust-lang.org/std/os/unix/net/struct.SocketAddr.html#method.is_unnamed) * [`SocketAddr::as_pathname`](http://doc.rust-lang.org/std/os/unix/net/struct.SocketAddr.html#method.as_pathname) * [`UnixStream::connect`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.connect) * [`UnixStream::pair`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.pair) * [`UnixStream::try_clone`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.try_clone) * [`UnixStream::local_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.local_addr) * [`UnixStream::peer_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.peer_addr) * [`UnixStream::set_read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.read_timeout) * [`UnixStream::set_write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.write_timeout) * [`UnixStream::read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.read_timeout) * [`UnixStream::write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.write_timeout) * [`UnixStream::set_nonblocking`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.set_nonblocking) * [`UnixStream::take_error`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.take_error) * [`UnixStream::shutdown`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html#method.shutdown) * Read/Write/RawFd impls for `UnixStream` * [`UnixListener::bind`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.bind) * [`UnixListener::accept`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.accept) * [`UnixListener::try_clone`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.try_clone) * [`UnixListener::local_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.local_addr) * [`UnixListener::set_nonblocking`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.set_nonblocking) * [`UnixListener::take_error`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.take_error) * [`UnixListener::incoming`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixListener.html#method.incoming) * RawFd impls for `UnixListener` * [`UnixDatagram::bind`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.bind) * [`UnixDatagram::unbound`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.unbound) * [`UnixDatagram::pair`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.pair) * [`UnixDatagram::connect`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.connect) * [`UnixDatagram::try_clone`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.try_clone) * [`UnixDatagram::local_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.local_addr) * [`UnixDatagram::peer_addr`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.peer_addr) * [`UnixDatagram::recv_from`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.recv_from) * [`UnixDatagram::recv`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.recv) * [`UnixDatagram::send_to`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.send_to) * [`UnixDatagram::send`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.send) * [`UnixDatagram::set_read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.set_read_timeout) * [`UnixDatagram::set_write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.set_write_timeout) * [`UnixDatagram::read_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.read_timeout) * [`UnixDatagram::write_timeout`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.write_timeout) * [`UnixDatagram::set_nonblocking`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.set_nonblocking) * [`UnixDatagram::take_error`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.take_error) * [`UnixDatagram::shutdown`](http://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.shutdown) * RawFd impls for `UnixDatagram` * `{BTree,Hash}Map::values_mut` * [`<[_]>::binary_search_by_key`](http://doc.rust-lang.org/std/primitive.slice.html#method.binary_search_by_key) [§](https://doc.rust-lang.org/stable/releases.html#libraries-82) Libraries -------------------------------------------------------------------------- * [The `abs_sub` method of floats is deprecated](https://github.com/rust-lang/rust/pull/33664) . The semantics of this minor method are subtle and probably not what most people want. * [Add implementation of Ord for Cell and RefCell where T: Ord](https://github.com/rust-lang/rust/pull/33306) . * [On Linux, if `HashMap`s can’t be initialized with `getrandom` they will fall back to `/dev/urandom` temporarily to avoid blocking during early boot](https://github.com/rust-lang/rust/pull/33086) . * [Implemented negation for wrapping numerals](https://github.com/rust-lang/rust/pull/33067) . * [Implement `Clone` for `binary_heap::IntoIter`](https://github.com/rust-lang/rust/pull/33050) . * [Implement `Display` and `Hash` for `std::num::Wrapping`](https://github.com/rust-lang/rust/pull/33023) . * [Add `Default` implementation for `&CStr`, `CString`](https://github.com/rust-lang/rust/pull/32990) . * [Implement `From>` and `Into>` for `VecDeque`](https://github.com/rust-lang/rust/pull/32866) . * [Implement `Default` for `UnsafeCell`, `fmt::Error`, `Condvar`, `Mutex`, `RwLock`](https://github.com/rust-lang/rust/pull/32785) . [§](https://doc.rust-lang.org/stable/releases.html#cargo-80) Cargo ------------------------------------------------------------------ * [Cargo.toml supports the `profile.*.panic` option](https://github.com/rust-lang/cargo/pull/2687) . This controls the runtime behavior of the `panic!` macro and can be either “unwind” (the default), or “abort”. [RFC 1513](https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md) . * [Don’t throw away errors with `-p` arguments](https://github.com/rust-lang/cargo/pull/2723) . * [Report status to stderr instead of stdout](https://github.com/rust-lang/cargo/pull/2693) . * [Build scripts are passed a `CARGO_MANIFEST_LINKS` environment variable that corresponds to the `links` field of the manifest](https://github.com/rust-lang/cargo/pull/2710) . * [Ban keywords from crate names](https://github.com/rust-lang/cargo/pull/2707) . * [Canonicalize `CARGO_HOME` on Windows](https://github.com/rust-lang/cargo/pull/2604) . * [Retry network requests](https://github.com/rust-lang/cargo/pull/2396) . By default they are retried twice, which can be customized with the `net.retry` value in `.cargo/config`. * [Don’t print extra error info for failing subcommands](https://github.com/rust-lang/cargo/pull/2674) . * [Add `--force` flag to `cargo install`](https://github.com/rust-lang/cargo/pull/2405) . * [Don’t use `flock` on NFS mounts](https://github.com/rust-lang/cargo/pull/2623) . * [Prefer building `cargo install` artifacts in temporary directories](https://github.com/rust-lang/cargo/pull/2610) . Makes it possible to install multiple crates in parallel. * [Add `cargo test --doc`](https://github.com/rust-lang/cargo/pull/2578) . * [Add `cargo --explain`](https://github.com/rust-lang/cargo/pull/2551) . * [Don’t print warnings when `-q` is passed](https://github.com/rust-lang/cargo/pull/2576) . * [Add `cargo doc --lib` and `--bin`](https://github.com/rust-lang/cargo/pull/2577) . * [Don’t require build script output to be UTF-8](https://github.com/rust-lang/cargo/pull/2560) . * [Correctly attempt multiple git usernames](https://github.com/rust-lang/cargo/pull/2584) . [§](https://doc.rust-lang.org/stable/releases.html#performance-2) Performance ----------------------------------------------------------------------------- * [rustc memory usage was reduced by refactoring the context used for type checking](https://github.com/rust-lang/rust/pull/33425) . * [Speed up creation of `HashMap`s by caching the random keys used to initialize the hash state](https://github.com/rust-lang/rust/pull/33318) . * [The `find` implementation for `Chain` iterators is 2x faster](https://github.com/rust-lang/rust/pull/33289) . * [Trait selection optimizations speed up type checking by 15%](https://github.com/rust-lang/rust/pull/33138) . * [Efficient trie lookup for boolean Unicode properties](https://github.com/rust-lang/rust/pull/33098) . 10x faster than the previous lookup tables. * [Special case `#[derive(Copy, Clone)]` to avoid bloat](https://github.com/rust-lang/rust/pull/31414) . [§](https://doc.rust-lang.org/stable/releases.html#usability) Usability ----------------------------------------------------------------------- * Many incremental improvements to documentation and rustdoc. * [rustdoc: List blanket trait impls](https://github.com/rust-lang/rust/pull/33514) . * [rustdoc: Clean up ABI rendering](https://github.com/rust-lang/rust/pull/33151) . * [Indexing with the wrong type produces a more informative error](https://github.com/rust-lang/rust/pull/33401) . * [Improve diagnostics for constants being used in irrefutable patterns](https://github.com/rust-lang/rust/pull/33406) . * [When many method candidates are in scope limit the suggestions to 10](https://github.com/rust-lang/rust/pull/33338) . * [Remove confusing suggestion when calling a `fn` type](https://github.com/rust-lang/rust/pull/33325) . * [Do not suggest changing `&mut self` to `&mut mut self`](https://github.com/rust-lang/rust/pull/33319) . [§](https://doc.rust-lang.org/stable/releases.html#misc-43) Misc ---------------------------------------------------------------- * [Update i686-linux-android features to match Android ABI](https://github.com/rust-lang/rust/pull/33651) . * [Update aarch64-linux-android features to match Android ABI](https://github.com/rust-lang/rust/pull/33500) . * [`std` no longer prints backtraces on platforms where the running module must be loaded with `env::current_exe`, which can’t be relied on](https://github.com/rust-lang/rust/pull/33554) . * This release includes std binaries for the i586-unknown-linux-gnu, i686-unknown-linux-musl, and armv7-linux-androideabi targets. The i586 target is for old x86 hardware without SSE2, and the armv7 target is for Android running on modern ARM architectures. * [The `rust-gdb` and `rust-lldb` scripts are distributed on all Unix platforms](https://github.com/rust-lang/rust/pull/32835) . * [On Unix the runtime aborts by calling `libc::abort` instead of generating an illegal instruction](https://github.com/rust-lang/rust/pull/31457) . * [Rust is now bootstrapped from the previous release of Rust, instead of a snapshot from an arbitrary commit](https://github.com/rust-lang/rust/pull/32942) . [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-82) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`AtomicBool` is now bool-sized, not word-sized](https://github.com/rust-lang/rust/pull/33579) . * [`target_env` for Linux ARM targets is just `gnu`, not `gnueabihf`, `gnueabi`, etc](https://github.com/rust-lang/rust/pull/33403) . * [Consistently panic on overflow in `Duration::new`](https://github.com/rust-lang/rust/pull/33072) . * [Change `String::truncate` to panic less](https://github.com/rust-lang/rust/pull/32977) . * [Add `:block` to the follow set for `:ty` and `:path`](https://github.com/rust-lang/rust/pull/32945) . Affects how macros are parsed. * [Fix macro hygiene bug](https://github.com/rust-lang/rust/pull/32923) . * [Feature-gated attributes on macro-generated macro invocations are now rejected](https://github.com/rust-lang/rust/pull/32791) . * [Suppress fallback and ambiguity errors during type inference](https://github.com/rust-lang/rust/pull/32258) . This caused some minor changes to type inference. [§](https://doc.rust-lang.org/stable/releases.html#version-190-2016-05-26) Version 1.9.0 (2016-05-26) ===================================================================================================== [§](https://doc.rust-lang.org/stable/releases.html#language-82) Language ------------------------------------------------------------------------ * The `#[deprecated]` attribute when applied to an API will generate warnings when used. The warnings may be suppressed with `#[allow(deprecated)]`. [RFC 1270](https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md) . * [`fn` item types are zero sized, and each `fn` names a unique type](https://github.com/rust-lang/rust/pull/31710) . This will break code that transmutes `fn`s, so calling `transmute` on a `fn` type will generate a warning for a few cycles, then will be converted to an error. * [Field and method resolution understand visibility, so private fields and methods cannot prevent the proper use of public fields and methods](https://github.com/rust-lang/rust/pull/31938) . * [The parser considers unicode codepoints in the `PATTERN_WHITE_SPACE` category to be whitespace](https://github.com/rust-lang/rust/pull/29734) . [§](https://doc.rust-lang.org/stable/releases.html#stabilized-apis-77) Stabilized APIs -------------------------------------------------------------------------------------- * [`std::panic`](http://doc.rust-lang.org/nightly/std/panic/index.html) * [`std::panic::catch_unwind`](http://doc.rust-lang.org/nightly/std/panic/fn.catch_unwind.html) (renamed from `recover`) * [`std::panic::resume_unwind`](http://doc.rust-lang.org/nightly/std/panic/fn.resume_unwind.html) (renamed from `propagate`) * [`std::panic::AssertUnwindSafe`](http://doc.rust-lang.org/nightly/std/panic/struct.AssertUnwindSafe.html) (renamed from `AssertRecoverSafe`) * [`std::panic::UnwindSafe`](http://doc.rust-lang.org/nightly/std/panic/trait.UnwindSafe.html) (renamed from `RecoverSafe`) * [`str::is_char_boundary`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.is_char_boundary) * [`<*const T>::as_ref`](http://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.as_ref) * [`<*mut T>::as_ref`](http://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.as_ref) * [`<*mut T>::as_mut`](http://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.as_mut) * [`AsciiExt::make_ascii_uppercase`](http://doc.rust-lang.org/nightly/std/ascii/trait.AsciiExt.html#tymethod.make_ascii_uppercase) * [`AsciiExt::make_ascii_lowercase`](http://doc.rust-lang.org/nightly/std/ascii/trait.AsciiExt.html#tymethod.make_ascii_lowercase) * [`char::decode_utf16`](https://doc.rust-lang.org/std/primitive.char.html#method.decode_utf16) * [`char::DecodeUtf16`](http://doc.rust-lang.org/nightly/std/char/struct.DecodeUtf16.html) * [`char::DecodeUtf16Error`](http://doc.rust-lang.org/nightly/std/char/struct.DecodeUtf16Error.html) * [`char::DecodeUtf16Error::unpaired_surrogate`](http://doc.rust-lang.org/nightly/std/char/struct.DecodeUtf16Error.html#method.unpaired_surrogate) * [`BTreeSet::take`](http://doc.rust-lang.org/nightly/collections/btree/set/struct.BTreeSet.html#method.take) * [`BTreeSet::replace`](http://doc.rust-lang.org/nightly/collections/btree/set/struct.BTreeSet.html#method.replace) * [`BTreeSet::get`](http://doc.rust-lang.org/nightly/collections/btree/set/struct.BTreeSet.html#method.get) * [`HashSet::take`](http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.take) * [`HashSet::replace`](http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.replace) * [`HashSet::get`](http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.get) * [`OsString::with_capacity`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.with_capacity) * [`OsString::clear`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.clear) * [`OsString::capacity`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.capacity) * [`OsString::reserve`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.reserve) * [`OsString::reserve_exact`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsString.html#method.reserve_exact) * [`OsStr::is_empty`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsStr.html#method.is_empty) * [`OsStr::len`](http://doc.rust-lang.org/nightly/std/ffi/struct.OsStr.html#method.len) * [`std::os::unix::thread`](http://doc.rust-lang.org/nightly/std/os/unix/thread/index.html) * [`RawPthread`](http://doc.rust-lang.org/nightly/std/os/unix/thread/type.RawPthread.html) * [`JoinHandleExt`](http://doc.rust-lang.org/nightly/std/os/unix/thread/trait.JoinHandleExt.html) * [`JoinHandleExt::as_pthread_t`](http://doc.rust-lang.org/nightly/std/os/unix/thread/trait.JoinHandleExt.html#tymethod.as_pthread_t) * [`JoinHandleExt::into_pthread_t`](http://doc.rust-lang.org/nightly/std/os/unix/thread/trait.JoinHandleExt.html#tymethod.into_pthread_t) * [`HashSet::hasher`](http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.hasher) * [`HashMap::hasher`](http://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html#method.hasher) * [`CommandExt::exec`](http://doc.rust-lang.org/nightly/std/os/unix/process/trait.CommandExt.html#tymethod.exec) * [`File::try_clone`](http://doc.rust-lang.org/nightly/std/fs/struct.File.html#method.try_clone) * [`SocketAddr::set_ip`](http://doc.rust-lang.org/nightly/std/net/enum.SocketAddr.html#method.set_ip) * [`SocketAddr::set_port`](http://doc.rust-lang.org/nightly/std/net/enum.SocketAddr.html#method.set_port) * [`SocketAddrV4::set_ip`](http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV4.html#method.set_ip) * [`SocketAddrV4::set_port`](http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV4.html#method.set_port) * [`SocketAddrV6::set_ip`](http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_ip) * [`SocketAddrV6::set_port`](http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_port) * [`SocketAddrV6::set_flowinfo`](http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_flowinfo) * [`SocketAddrV6::set_scope_id`](http://doc.rust-lang.org/nightly/std/net/struct.SocketAddrV6.html#method.set_scope_id) * [`slice::copy_from_slice`](http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.copy_from_slice) * [`ptr::read_volatile`](http://doc.rust-lang.org/nightly/std/ptr/fn.read_volatile.html) * [`ptr::write_volatile`](http://doc.rust-lang.org/nightly/std/ptr/fn.write_volatile.html) * [`OpenOptions::create_new`](http://doc.rust-lang.org/nightly/std/fs/struct.OpenOptions.html#method.create_new) * [`TcpStream::set_nodelay`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_nodelay) * [`TcpStream::nodelay`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.nodelay) * [`TcpStream::set_ttl`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_ttl) * [`TcpStream::ttl`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.ttl) * [`TcpStream::set_only_v6`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_only_v6) * [`TcpStream::only_v6`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.only_v6) * [`TcpStream::take_error`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.take_error) * [`TcpStream::set_nonblocking`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_nonblocking) * [`TcpListener::set_ttl`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_ttl) * [`TcpListener::ttl`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.ttl) * [`TcpListener::set_only_v6`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_only_v6) * [`TcpListener::only_v6`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.only_v6) * [`TcpListener::take_error`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.take_error) * [`TcpListener::set_nonblocking`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_nonblocking) * [`UdpSocket::set_broadcast`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_broadcast) * [`UdpSocket::broadcast`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.broadcast) * [`UdpSocket::set_multicast_loop_v4`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_loop_v4) * [`UdpSocket::multicast_loop_v4`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_loop_v4) * [`UdpSocket::set_multicast_ttl_v4`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_ttl_v4) * [`UdpSocket::multicast_ttl_v4`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_ttl_v4) * [`UdpSocket::set_multicast_loop_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_loop_v6) * [`UdpSocket::multicast_loop_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_loop_v6) * [`UdpSocket::set_multicast_ttl_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_multicast_ttl_v6) * [`UdpSocket::multicast_ttl_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.multicast_ttl_v6) * [`UdpSocket::set_ttl`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_ttl) * [`UdpSocket::ttl`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.ttl) * [`UdpSocket::set_only_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_only_v6) * [`UdpSocket::only_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.only_v6) * [`UdpSocket::join_multicast_v4`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.join_multicast_v4) * [`UdpSocket::join_multicast_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.join_multicast_v6) * [`UdpSocket::leave_multicast_v4`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.leave_multicast_v4) * [`UdpSocket::leave_multicast_v6`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.leave_multicast_v6) * [`UdpSocket::take_error`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.take_error) * [`UdpSocket::connect`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.connect) * [`UdpSocket::send`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.send) * [`UdpSocket::recv`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.recv) * [`UdpSocket::set_nonblocking`](http://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.set_nonblocking) [§](https://doc.rust-lang.org/stable/releases.html#libraries-83) Libraries -------------------------------------------------------------------------- * [`std::sync::Once` is poisoned if its initialization function fails](https://github.com/rust-lang/rust/pull/32325) . * [`cell::Ref` and `cell::RefMut` can contain unsized types](https://github.com/rust-lang/rust/pull/32652) . * [Most types implement `fmt::Debug`](https://github.com/rust-lang/rust/pull/32054) . * [The default buffer size used by `BufReader` and `BufWriter` was reduced to 8K, from 64K](https://github.com/rust-lang/rust/pull/32695) . This is in line with the buffer size used by other languages. * [`Instant`, `SystemTime` and `Duration` implement `+=` and `-=`. `Duration` additionally implements `*=` and `/=`](https://github.com/rust-lang/rust/pull/32448) . * [`Skip` is a `DoubleEndedIterator`](https://github.com/rust-lang/rust/pull/31700) . * [`From<[u8; 4]>` is implemented for `Ipv4Addr`](https://github.com/rust-lang/rust/pull/32050) . * [`Chain` implements `BufRead`](https://github.com/rust-lang/rust/pull/32541) . * [`HashMap`, `HashSet` and iterators are covariant](https://github.com/rust-lang/rust/pull/32635) . [§](https://doc.rust-lang.org/stable/releases.html#cargo-81) Cargo ------------------------------------------------------------------ * [Cargo can now run concurrently](https://github.com/rust-lang/cargo/pull/2486) . * [Top-level overrides allow specific revisions of crates to be overridden through the entire crate graph](https://github.com/rust-lang/cargo/pull/2385) . This is intended to make upgrades easier for large projects, by allowing crates to be forked temporarily until they’ve been upgraded and republished. * [Cargo exports a `CARGO_PKG_AUTHORS` environment variable](https://github.com/rust-lang/cargo/pull/2465) . * [Cargo will pass the contents of the `RUSTFLAGS` variable to `rustc` on the commandline](https://github.com/rust-lang/cargo/pull/2241) . `rustc` arguments can also be specified in the `build.rustflags` configuration key. [§](https://doc.rust-lang.org/stable/releases.html#performance-3) Performance ----------------------------------------------------------------------------- * [The time complexity of comparing variables for equivalence during type unification is reduced from _O_(_n_!) to _O_(_n_)](https://github.com/rust-lang/rust/pull/32062) . This leads to major compilation time improvement in some scenarios. * [`ToString` is specialized for `str`, giving it the same performance as `to_owned`](https://github.com/rust-lang/rust/pull/32586) . * [Spawning processes with `Command::output` no longer creates extra threads](https://github.com/rust-lang/rust/pull/31618) . * [`#[derive(PartialEq)]` and `#[derive(PartialOrd)]` emit less code for C-like enums](https://github.com/rust-lang/rust/pull/31977) . [§](https://doc.rust-lang.org/stable/releases.html#misc-44) Misc ---------------------------------------------------------------- * [Passing the `--quiet` flag to a test runner will produce much-abbreviated output](https://github.com/rust-lang/rust/pull/31887) . * The Rust Project now publishes std binaries for the `mips-unknown-linux-musl`, `mipsel-unknown-linux-musl`, and `i586-pc-windows-msvc` targets. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-83) Compatibility Notes ---------------------------------------------------------------------------------------------- * [`std::sync::Once` is poisoned if its initialization function fails](https://github.com/rust-lang/rust/pull/32325) . * [It is illegal to define methods with the same name in overlapping inherent `impl` blocks](https://github.com/rust-lang/rust/pull/31925) . * [`fn` item types are zero sized, and each `fn` names a unique type](https://github.com/rust-lang/rust/pull/31710) . This will break code that transmutes `fn`s, so calling `transmute` on a `fn` type will generate a warning for a few cycles, then will be converted to an error. * [Improvements to const evaluation may trigger new errors when integer literals are out of range](https://github.com/rust-lang/rust/pull/30587) . [§](https://doc.rust-lang.org/stable/releases.html#version-180-2016-04-14) Version 1.8.0 (2016-04-14) ===================================================================================================== [§](https://doc.rust-lang.org/stable/releases.html#language-83) Language ------------------------------------------------------------------------ * Rust supports overloading of compound assignment statements like `+=` by implementing the [`AddAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.AddAssign.html) , [`SubAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.SubAssign.html) , [`MulAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.MulAssign.html) , [`DivAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.DivAssign.html) , [`RemAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.RemAssign.html) , [`BitAndAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.BitAndAssign.html) , [`BitOrAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.BitOrAssign.html) , [`BitXorAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.BitXorAssign.html) , [`ShlAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.ShlAssign.html) , or [`ShrAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.ShrAssign.html) traits. [RFC 953](https://github.com/rust-lang/rfcs/blob/master/text/0953-op-assign.md) . * Empty structs can be defined with braces, as in `struct Foo { }`, in addition to the non-braced form, `struct Foo;`. [RFC 218](https://github.com/rust-lang/rfcs/blob/master/text/0218-empty-struct-with-braces.md) . [§](https://doc.rust-lang.org/stable/releases.html#libraries-84) Libraries -------------------------------------------------------------------------- * Stabilized APIs: * [`str::encode_utf16`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.encode_utf16) (renamed from `utf16_units`) * [`str::EncodeUtf16`](http://doc.rust-lang.org/nightly/std/str/struct.EncodeUtf16.html) (renamed from `Utf16Units`) * [`Ref::map`](http://doc.rust-lang.org/nightly/std/cell/struct.Ref.html#method.map) * [`RefMut::map`](http://doc.rust-lang.org/nightly/std/cell/struct.RefMut.html#method.map) * [`ptr::drop_in_place`](http://doc.rust-lang.org/nightly/std/ptr/fn.drop_in_place.html) * [`time::Instant`](http://doc.rust-lang.org/nightly/std/time/struct.Instant.html) * [`time::SystemTime`](http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html) * [`Instant::now`](http://doc.rust-lang.org/nightly/std/time/struct.Instant.html#method.now) * [`Instant::duration_since`](http://doc.rust-lang.org/nightly/std/time/struct.Instant.html#method.duration_since) (renamed from `duration_from_earlier`) * [`Instant::elapsed`](http://doc.rust-lang.org/nightly/std/time/struct.Instant.html#method.elapsed) * [`SystemTime::now`](http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#method.now) * [`SystemTime::duration_since`](http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#method.duration_since) (renamed from `duration_from_earlier`) * [`SystemTime::elapsed`](http://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#method.elapsed) * Various `Add`/`Sub` impls for `Time` and `SystemTime` * [`SystemTimeError`](http://doc.rust-lang.org/nightly/std/time/struct.SystemTimeError.html) * [`SystemTimeError::duration`](http://doc.rust-lang.org/nightly/std/time/struct.SystemTimeError.html#method.duration) * Various impls for `SystemTimeError` * [`UNIX_EPOCH`](http://doc.rust-lang.org/nightly/std/time/constant.UNIX_EPOCH.html) * [`AddAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.AddAssign.html) , [`SubAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.SubAssign.html) , [`MulAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.MulAssign.html) , [`DivAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.DivAssign.html) , [`RemAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.RemAssign.html) , [`BitAndAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.BitAndAssign.html) , [`BitOrAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.BitOrAssign.html) , [`BitXorAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.BitXorAssign.html) , [`ShlAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.ShlAssign.html) , [`ShrAssign`](http://doc.rust-lang.org/nightly/std/ops/trait.ShrAssign.html) . * [The `write!` and `writeln!` macros correctly emit errors if any of their arguments can’t be formatted](https://github.com/rust-lang/rust/pull/31904) . * [Various I/O functions support large files on 32-bit Linux](https://github.com/rust-lang/rust/pull/31668) . * [The Unix-specific `raw` modules, which contain a number of redefined C types are deprecated](https://github.com/rust-lang/rust/pull/31551) , including `os::raw::unix`, `os::raw::macos`, and `os::raw::linux`. These modules defined types such as `ino_t` and `dev_t`. The inconsistency of these definitions across platforms was making it difficult to implement `std` correctly. Those that need these definitions should use the `libc` crate. [RFC 1415](https://github.com/rust-lang/rfcs/blob/master/text/1415-trim-std-os.md) . * The Unix-specific `MetadataExt` traits, including `os::unix::fs::MetadataExt`, which expose values such as inode numbers [no longer return platform-specific types](https://github.com/rust-lang/rust/pull/31551) , but instead return widened integers. [RFC 1415](https://github.com/rust-lang/rfcs/blob/master/text/1415-trim-std-os.md) . * [`btree_set::{IntoIter, Iter, Range}` are covariant](https://github.com/rust-lang/rust/pull/30998) . * [Atomic loads and stores are not volatile](https://github.com/rust-lang/rust/pull/30962) . * [All types in `sync::mpsc` implement `fmt::Debug`](https://github.com/rust-lang/rust/pull/30894) . [§](https://doc.rust-lang.org/stable/releases.html#performance-4) Performance ----------------------------------------------------------------------------- * [Inlining hash functions lead to a 3% compile-time improvement in some workloads](https://github.com/rust-lang/rust/pull/31460) . * When using jemalloc, its symbols are [unprefixed so that it overrides the libc malloc implementation](https://github.com/rust-lang/rust/pull/31460) . This means that for rustc, LLVM is now using jemalloc, which results in a 6% compile-time improvement on a specific workload. * [Avoid quadratic growth in function size due to cleanups](https://github.com/rust-lang/rust/pull/31390) . [§](https://doc.rust-lang.org/stable/releases.html#misc-45) Misc ---------------------------------------------------------------- * [32-bit MSVC builds finally implement unwinding](https://github.com/rust-lang/rust/pull/30448) . i686-pc-windows-msvc is now considered a tier-1 platform. * [The `--print targets` flag prints a list of supported targets](https://github.com/rust-lang/rust/pull/31358) . * [The `--print cfg` flag prints the `cfg`s defined for the current target](https://github.com/rust-lang/rust/pull/31278) . * [`rustc` can be built with an new Cargo-based build system, written in Rust](https://github.com/rust-lang/rust/pull/31123) . It will eventually replace Rust’s Makefile-based build system. To enable it configure with `configure --rustbuild`. * [Errors for non-exhaustive `match` patterns now list up to 3 missing variants while also indicating the total number of missing variants if more than 3](https://github.com/rust-lang/rust/pull/31020) . * [Executable stacks are disabled on Linux and BSD](https://github.com/rust-lang/rust/pull/30859) . * The Rust Project now publishes binary releases of the standard library for a number of tier-2 targets: `armv7-unknown-linux-gnueabihf`, `powerpc-unknown-linux-gnu`, `powerpc64-unknown-linux-gnu`, `powerpc64le-unknown-linux-gnu` `x86_64-rumprun-netbsd`. These can be installed with tools such as [multirust](https://users.rust-lang.org/t/multirust-0-8-with-cross-std-installation/4901) . [§](https://doc.rust-lang.org/stable/releases.html#cargo-82) Cargo ------------------------------------------------------------------ * [`cargo init` creates a new Cargo project in the current directory](https://github.com/rust-lang/cargo/pull/2081) . It is otherwise like `cargo new`. * [Cargo has configuration keys for `-v` and `--color`](https://github.com/rust-lang/cargo/pull/2397) . `verbose` and `color`, respectively, go in the `[term]` section of `.cargo/config`. * [Configuration keys that evaluate to strings or integers can be set via environment variables](https://github.com/rust-lang/cargo/pull/2398) . For example the `build.jobs` key can be set via `CARGO_BUILD_JOBS`. Environment variables take precedence over config files. * [Target-specific dependencies support Rust `cfg` syntax for describing targets](https://github.com/rust-lang/cargo/pull/2328) so that dependencies for multiple targets can be specified together. [RFC 1361](https://github.com/rust-lang/rfcs/blob/master/text/1361-cargo-cfg-dependencies.md) . * [The environment variables `CARGO_TARGET_ROOT`, `RUSTC`, and `RUSTDOC` take precedence over the `build.target-dir`, `build.rustc`, and `build.rustdoc` configuration values](https://github.com/rust-lang/cargo/issues/2365) . * [The child process tree is killed on Windows when Cargo is killed](https://github.com/rust-lang/cargo/pull/2370) . * [The `build.target` configuration value sets the target platform, like `--target`](https://github.com/rust-lang/cargo/pull/2335) . [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-84) Compatibility Notes ---------------------------------------------------------------------------------------------- * [Unstable compiler flags have been further restricted](https://github.com/rust-lang/rust/pull/31793) . Since 1.0 `-Z` flags have been considered unstable, and other flags that were considered unstable additionally required passing `-Z unstable-options` to access. Unlike unstable language and library features though, these options have been accessible on the stable release channel. Going forward, _new unstable flags will not be available on the stable release channel_, and old unstable flags will warn about their usage. In the future, all unstable flags will be unavailable on the stable release channel. * [It is no longer possible to `match` on empty enum variants using the `Variant(..)` syntax](https://github.com/rust-lang/rust/pull/31757) . This has been a warning since 1.6. * The Unix-specific `MetadataExt` traits, including `os::unix::fs::MetadataExt`, which expose values such as inode numbers [no longer return platform-specific types](https://github.com/rust-lang/rust/pull/31551) , but instead return widened integers. [RFC 1415](https://github.com/rust-lang/rfcs/blob/master/text/1415-trim-std-os.md) . * [Modules sourced from the filesystem cannot appear within arbitrary blocks, but only within other modules](https://github.com/rust-lang/rust/pull/31534) . * [`--cfg` compiler flags are parsed strictly as identifiers](https://github.com/rust-lang/rust/pull/31530) . * On Unix, [stack overflow triggers a runtime abort instead of a SIGSEGV](https://github.com/rust-lang/rust/pull/31333) . * [`Command::spawn` and its equivalents return an error if any of its command-line arguments contain interior `NUL`s](https://github.com/rust-lang/rust/pull/31056) . * [Tuple and unit enum variants from other crates are in the type namespace](https://github.com/rust-lang/rust/pull/30882) . * [On Windows `rustc` emits `.lib` files for the `staticlib` library type instead of `.a` files](https://github.com/rust-lang/rust/pull/29520) . Additionally, for the MSVC toolchain, `rustc` emits import libraries named `foo.dll.lib` instead of `foo.lib`. [§](https://doc.rust-lang.org/stable/releases.html#version-170-2016-03-03) Version 1.7.0 (2016-03-03) ===================================================================================================== [§](https://doc.rust-lang.org/stable/releases.html#libraries-85) Libraries -------------------------------------------------------------------------- * Stabilized APIs * `Path` * [`Path::strip_prefix`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.strip_prefix) (renamed from relative\_from) * [`path::StripPrefixError`](http://doc.rust-lang.org/nightly/std/path/struct.StripPrefixError.html) (new error type returned from strip\_prefix) * `Ipv4Addr` * [`Ipv4Addr::is_loopback`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_loopback) * [`Ipv4Addr::is_private`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_private) * [`Ipv4Addr::is_link_local`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_link_local) * [`Ipv4Addr::is_multicast`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_multicast) * [`Ipv4Addr::is_broadcast`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_broadcast) * [`Ipv4Addr::is_documentation`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_documentation) * `Ipv6Addr` * [`Ipv6Addr::is_unspecified`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_unspecified) * [`Ipv6Addr::is_loopback`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_loopback) * [`Ipv6Addr::is_multicast`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_multicast) * `Vec` * [`Vec::as_slice`](http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.as_slice) * [`Vec::as_mut_slice`](http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.as_mut_slice) * `String` * [`String::as_str`](http://doc.rust-lang.org/nightly/std/string/struct.String.html#method.as_str) * [`String::as_mut_str`](http://doc.rust-lang.org/nightly/std/string/struct.String.html#method.as_mut_str) * Slices * `<[T]>::`[`clone_from_slice`](http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.clone_from_slice) , which now requires the two slices to be the same length * `<[T]>::`[`sort_by_key`](http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.sort_by_key) * checked, saturated, and overflowing operations * [`i32::checked_rem`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_rem) , [`i32::checked_neg`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_neg) , [`i32::checked_shl`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_shl) , [`i32::checked_shr`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.checked_shr) * [`i32::saturating_mul`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.saturating_mul) * [`i32::overflowing_add`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_add) , [`i32::overflowing_sub`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_sub) , [`i32::overflowing_mul`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_mul) , [`i32::overflowing_div`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_div) * [`i32::overflowing_rem`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_rem) , [`i32::overflowing_neg`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_neg) , [`i32::overflowing_shl`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_shl) , [`i32::overflowing_shr`](http://doc.rust-lang.org/nightly/std/primitive.i32.html#method.overflowing_shr) * [`u32::checked_rem`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_rem) , [`u32::checked_neg`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_neg) , [`u32::checked_shl`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_shl) , [`u32::checked_shl`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.checked_shl) * [`u32::saturating_mul`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.saturating_mul) * [`u32::overflowing_add`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_add) , [`u32::overflowing_sub`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_sub) , [`u32::overflowing_mul`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_mul) , [`u32::overflowing_div`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_div) * [`u32::overflowing_rem`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_rem) , [`u32::overflowing_neg`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_neg) , [`u32::overflowing_shl`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_shl) , [`u32::overflowing_shr`](http://doc.rust-lang.org/nightly/std/primitive.u32.html#method.overflowing_shr) * and checked, saturated, and overflowing operations for other primitive types * FFI * [`ffi::IntoStringError`](http://doc.rust-lang.org/nightly/std/ffi/struct.IntoStringError.html) * [`CString::into_string`](http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_string) * [`CString::into_bytes`](http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_bytes) * [`CString::into_bytes_with_nul`](http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_bytes_with_nul) * `From for Vec` * `IntoStringError` * [`IntoStringError::into_cstring`](http://doc.rust-lang.org/nightly/std/ffi/struct.IntoStringError.html#method.into_cstring) * [`IntoStringError::utf8_error`](http://doc.rust-lang.org/nightly/std/ffi/struct.IntoStringError.html#method.utf8_error) * `Error for IntoStringError` * Hashing * [`std::hash::BuildHasher`](http://doc.rust-lang.org/nightly/std/hash/trait.BuildHasher.html) * [`BuildHasher::Hasher`](http://doc.rust-lang.org/nightly/std/hash/trait.Hasher.html) * [`BuildHasher::build_hasher`](http://doc.rust-lang.org/nightly/std/hash/trait.BuildHasher.html#tymethod.build_hasher) * [`std::hash::BuildHasherDefault`](http://doc.rust-lang.org/nightly/std/hash/struct.BuildHasherDefault.html) * [`HashMap::with_hasher`](http://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html#method.with_hasher) * [`HashMap::with_capacity_and_hasher`](http://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html#method.with_capacity_and_hasher) * [`HashSet::with_hasher`](http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.with_hasher) * [`HashSet::with_capacity_and_hasher`](http://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.with_capacity_and_hasher) * [`std::collections::hash_map::RandomState`](http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.RandomState.html) * [`RandomState::new`](http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.RandomState.html#method.new) * [Validating UTF-8 is faster by a factor of between 7 and 14x for ASCII input](https://github.com/rust-lang/rust/pull/30740) . This means that creating `String`s and `str`s from bytes is faster. * [The performance of `LineWriter` (and thus `io::stdout`) was improved by using `memchr` to search for newlines](https://github.com/rust-lang/rust/pull/30381) . * [`f32::to_degrees` and `f32::to_radians` are stable](https://github.com/rust-lang/rust/pull/30672) . The `f64` variants were stabilized previously. * [`BTreeMap` was rewritten to use less memory and improve the performance of insertion and iteration, the latter by as much as 5x](https://github.com/rust-lang/rust/pull/30426) . * [`BTreeSet` and its iterators, `Iter`, `IntoIter`, and `Range` are covariant over their contained type](https://github.com/rust-lang/rust/pull/30998) . * [`LinkedList` and its iterators, `Iter` and `IntoIter` are covariant over their contained type](https://github.com/rust-lang/rust/pull/30663) . * [`str::replace` now accepts a `Pattern`](https://github.com/rust-lang/rust/pull/29498) , like other string searching methods. * [`Any` is implemented for unsized types](https://github.com/rust-lang/rust/pull/30928) . * [`Hash` is implemented for `Duration`](https://github.com/rust-lang/rust/pull/30818) . [§](https://doc.rust-lang.org/stable/releases.html#misc-46) Misc ---------------------------------------------------------------- * [When running tests with `--test`, rustdoc will pass `--cfg` arguments to the compiler](https://github.com/rust-lang/rust/pull/30372) . * [The compiler is built with RPATH information by default](https://github.com/rust-lang/rust/pull/30353) . This means that it will be possible to run `rustc` when installed in unusual configurations without configuring the dynamic linker search path explicitly. * [`rustc` passes `--enable-new-dtags` to GNU ld](https://github.com/rust-lang/rust/pull/30394) . This makes any RPATH entries (emitted with `-C rpath`) _not_ take precedence over `LD_LIBRARY_PATH`. [§](https://doc.rust-lang.org/stable/releases.html#cargo-83) Cargo ------------------------------------------------------------------ * [`cargo rustc` accepts a `--profile` flag that runs `rustc` under any of the compilation profiles, ‘dev’, ‘bench’, or ‘test’](https://github.com/rust-lang/cargo/pull/2224) . * [The `rerun-if-changed` build script directive no longer causes the build script to incorrectly run twice in certain scenarios](https://github.com/rust-lang/cargo/pull/2279) . [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-85) Compatibility Notes ---------------------------------------------------------------------------------------------- * Soundness fixes to the interactions between associated types and lifetimes, specified in [RFC 1214](https://github.com/rust-lang/rfcs/blob/master/text/1214-projections-lifetimes-and-wf.md) , [now generate errors](https://github.com/rust-lang/rust/pull/30389) for code that violates the new rules. This is a significant change that is known to break existing code, so it has emitted warnings for the new error cases since 1.4 to give crate authors time to adapt. The details of what is changing are subtle; read the RFC for more. * [Several bugs in the compiler’s visibility calculations were fixed](https://github.com/rust-lang/rust/pull/29973) . Since this was found to break significant amounts of code, the new errors will be emitted as warnings for several release cycles, under the `private_in_public` lint. * Defaulted type parameters were accidentally accepted in positions that were not intended. In this release, [defaulted type parameters appearing outside of type definitions will generate a warning](https://github.com/rust-lang/rust/pull/30724) , which will become an error in future releases. * [Parsing “.” as a float results in an error instead of 0](https://github.com/rust-lang/rust/pull/30681) . That is, `".".parse::()` returns `Err`, not `Ok(0.0)`. * [Borrows of closure parameters may not outlive the closure](https://github.com/rust-lang/rust/pull/30341) . [§](https://doc.rust-lang.org/stable/releases.html#version-160-2016-01-21) Version 1.6.0 (2016-01-21) ===================================================================================================== [§](https://doc.rust-lang.org/stable/releases.html#language-84) Language ------------------------------------------------------------------------ * The `#![no_std]` attribute causes a crate to not be linked to the standard library, but only the [core library](http://doc.rust-lang.org/core/index.html) , as described in [RFC 1184](https://github.com/rust-lang/rfcs/blob/master/text/1184-stabilize-no_std.md) . The core library defines common types and traits but has no platform dependencies whatsoever, and is the basis for Rust software in environments that cannot support a full port of the standard library, such as operating systems. Most of the core library is now stable. [§](https://doc.rust-lang.org/stable/releases.html#libraries-86) Libraries -------------------------------------------------------------------------- * Stabilized APIs: [`Read::read_exact`](http://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_exact) , [`ErrorKind::UnexpectedEof`](http://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html#variant.UnexpectedEof) (renamed from `UnexpectedEOF`), [`fs::DirBuilder`](http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html) , [`fs::DirBuilder::new`](http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html#method.new) , [`fs::DirBuilder::recursive`](http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html#method.recursive) , [`fs::DirBuilder::create`](http://doc.rust-lang.org/nightly/std/fs/struct.DirBuilder.html#method.create) , [`os::unix::fs::DirBuilderExt`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.DirBuilderExt.html) , [`os::unix::fs::DirBuilderExt::mode`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.DirBuilderExt.html#tymethod.mode) , [`vec::Drain`](http://doc.rust-lang.org/nightly/std/vec/struct.Drain.html) , [`vec::Vec::drain`](http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.drain) , [`string::Drain`](http://doc.rust-lang.org/nightly/std/string/struct.Drain.html) , [`string::String::drain`](http://doc.rust-lang.org/nightly/std/string/struct.String.html#method.drain) , [`vec_deque::Drain`](http://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.Drain.html) , [`vec_deque::VecDeque::drain`](http://doc.rust-lang.org/nightly/std/collections/vec_deque/struct.VecDeque.html#method.drain) , [`collections::hash_map::Drain`](http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.Drain.html) , [`collections::hash_map::HashMap::drain`](http://doc.rust-lang.org/nightly/std/collections/hash_map/struct.HashMap.html#method.drain) , [`collections::hash_set::Drain`](http://doc.rust-lang.org/nightly/std/collections/hash_set/struct.Drain.html) , [`collections::hash_set::HashSet::drain`](http://doc.rust-lang.org/nightly/std/collections/hash_set/struct.HashSet.html#method.drain) , [`collections::binary_heap::Drain`](http://doc.rust-lang.org/nightly/std/collections/binary_heap/struct.Drain.html) , [`collections::binary_heap::BinaryHeap::drain`](http://doc.rust-lang.org/nightly/std/collections/binary_heap/struct.BinaryHeap.html#method.drain) , [`Vec::extend_from_slice`](http://doc.rust-lang.org/nightly/collections/vec/struct.Vec.html#method.extend_from_slice) (renamed from `push_all`), [`Mutex::get_mut`](http://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#method.get_mut) , [`Mutex::into_inner`](http://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#method.into_inner) , [`RwLock::get_mut`](http://doc.rust-lang.org/nightly/std/sync/struct.RwLock.html#method.get_mut) , [`RwLock::into_inner`](http://doc.rust-lang.org/nightly/std/sync/struct.RwLock.html#method.into_inner) , [`Iterator::min_by_key`](http://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.min_by_key) (renamed from `min_by`), [`Iterator::max_by_key`](http://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.max_by_key) (renamed from `max_by`). * The [core library](http://doc.rust-lang.org/core/index.html) is stable, as are most of its APIs. * [The `assert_eq!` macro supports arguments that don’t implement `Sized`](https://github.com/rust-lang/rust/pull/29770) , such as arrays. In this way it behaves more like `assert!`. * Several timer functions that take duration in milliseconds [are deprecated in favor of those that take `Duration`](https://github.com/rust-lang/rust/pull/29604) . These include `Condvar::wait_timeout_ms`, `thread::sleep_ms`, and `thread::park_timeout_ms`. * The algorithm by which `Vec` reserves additional elements was [tweaked to not allocate excessive space](https://github.com/rust-lang/rust/pull/29454) while still growing exponentially. * `From` conversions are [implemented from integers to floats](https://github.com/rust-lang/rust/pull/29129) in cases where the conversion is lossless. Thus they are not implemented for 32-bit ints to `f32`, nor for 64-bit ints to `f32` or `f64`. They are also not implemented for `isize` and `usize` because the implementations would be platform-specific. `From` is also implemented from `f32` to `f64`. * `From<&Path>` and `From` are implemented for `Cow`. * `From` is implemented for `Box`, `Rc` and `Arc`. * `IntoIterator` is implemented for `&PathBuf` and `&Path`. * [`BinaryHeap` was refactored](https://github.com/rust-lang/rust/pull/29811) for modest performance improvements. * Sorting slices that are already sorted [is 50% faster in some cases](https://github.com/rust-lang/rust/pull/29675) . [§](https://doc.rust-lang.org/stable/releases.html#cargo-84) Cargo ------------------------------------------------------------------ * Cargo will look in `$CARGO_HOME/bin` for subcommands [by default](https://github.com/rust-lang/cargo/pull/2192) . * Cargo build scripts can specify their dependencies by emitting the [`rerun-if-changed`](https://github.com/rust-lang/cargo/pull/2134) key. * crates.io will reject publication of crates with dependencies that have a wildcard version constraint. Crates with wildcard dependencies were seen to cause a variety of problems, as described in [RFC 1241](https://github.com/rust-lang/rfcs/blob/master/text/1241-no-wildcard-deps.md) . Since 1.5 publication of such crates has emitted a warning. * `cargo clean` [accepts a `--release` flag](https://github.com/rust-lang/cargo/pull/2131) to clean the release folder. A variety of artifacts that Cargo failed to clean are now correctly deleted. [§](https://doc.rust-lang.org/stable/releases.html#misc-47) Misc ---------------------------------------------------------------- * The `unreachable_code` lint [warns when a function call’s argument diverges](https://github.com/rust-lang/rust/pull/30000) . * The parser indicates [failures that may be caused by confusingly-similar Unicode characters](https://github.com/rust-lang/rust/pull/29837) * Certain macro errors [are reported at definition time](https://github.com/rust-lang/rust/pull/29828) , not expansion. [§](https://doc.rust-lang.org/stable/releases.html#compatibility-notes-86) Compatibility Notes ---------------------------------------------------------------------------------------------- * The compiler no longer makes use of the [`RUST_PATH`](https://github.com/rust-lang/rust/pull/30034) environment variable when locating crates. This was a pre-cargo feature for integrating with the package manager that was accidentally never removed. * [A number of bugs were fixed in the privacy checker](https://github.com/rust-lang/rust/pull/29726) that could cause previously-accepted code to break. * [Modules and unit/tuple structs may not share the same name](https://github.com/rust-lang/rust/issues/21546) . * [Bugs in pattern matching unit structs were fixed](https://github.com/rust-lang/rust/pull/29383) . The tuple struct pattern syntax (`Foo(..)`) can no longer be used to match unit structs. This is a warning now, but will become an error in future releases. Patterns that share the same name as a const are now an error. * A bug was fixed that causes [rustc not to apply default type parameters](https://github.com/rust-lang/rust/issues/30123) when resolving certain method implementations of traits defined in other crates. [§](https://doc.rust-lang.org/stable/releases.html#version-150-2015-12-10) Version 1.5.0 (2015-12-10) ===================================================================================================== * ~700 changes, numerous bugfixes [§](https://doc.rust-lang.org/stable/releases.html#highlights-1) Highlights --------------------------------------------------------------------------- * Stabilized APIs: [`BinaryHeap::from`](http://doc.rust-lang.org/nightly/std/convert/trait.From.html#method.from) , [`BinaryHeap::into_sorted_vec`](http://doc.rust-lang.org/nightly/std/collections/struct.BinaryHeap.html#method.into_sorted_vec) , [`BinaryHeap::into_vec`](http://doc.rust-lang.org/nightly/std/collections/struct.BinaryHeap.html#method.into_vec) , [`Condvar::wait_timeout`](http://doc.rust-lang.org/nightly/std/sync/struct.Condvar.html#method.wait_timeout) , [`FileTypeExt::is_block_device`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_block_device) , [`FileTypeExt::is_char_device`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_char_device) , [`FileTypeExt::is_fifo`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_fifo) , [`FileTypeExt::is_socket`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html#tymethod.is_socket) , [`FileTypeExt`](http://doc.rust-lang.org/nightly/std/os/unix/fs/trait.FileTypeExt.html) , [`Formatter::alternate`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.alternate) , [`Formatter::fill`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.fill) , [`Formatter::precision`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.precision) , [`Formatter::sign_aware_zero_pad`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.sign_aware_zero_pad) , [`Formatter::sign_minus`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.sign_minus) , [`Formatter::sign_plus`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.sign_plus) , [`Formatter::width`](http://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.width) , [`Iterator::cmp`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.cmp) , [`Iterator::eq`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.eq) , [`Iterator::ge`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.ge) , [`Iterator::gt`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.gt) , [`Iterator::le`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.le) , [`Iterator::lt`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.lt) , [`Iterator::ne`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.ne) , [`Iterator::partial_cmp`](http://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html#method.partial_cmp) , [`Path::canonicalize`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.canonicalize) , [`Path::exists`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.exists) , [`Path::is_dir`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.is_dir) , [`Path::is_file`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.is_file) , [`Path::metadata`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.metadata) , [`Path::read_dir`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.read_dir) , [`Path::read_link`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.read_link) , [`Path::symlink_metadata`](http://doc.rust-lang.org/nightly/std/path/struct.Path.html#method.symlink_metadata) , [`Utf8Error::valid_up_to`](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html#method.valid_up_to) , [`Vec::resize`](http://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.resize) , [`VecDeque::as_mut_slices`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.as_mut_slices) , [`VecDeque::as_slices`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.as_slices) , [`VecDeque::insert`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.insert) , [`VecDeque::shrink_to_fit`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.shrink_to_fit) , [`VecDeque::swap_remove_back`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.swap_remove_back) , [`VecDeque::swap_remove_front`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.swap_remove_front) , [`slice::split_first_mut`](http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_first_mut) , [`slice::split_first`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_first) , [`slice::split_last_mut`](http://doc.rust-lang.org/nightly/std/primitive.slice.html#method.split_last_mut) , [`slice::split_last`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_last) , [`char::from_u32_unchecked`](https://doc.rust-lang.org/std/primitive.char.html#method.from_u32_unchecked) , [`fs::canonicalize`](http://doc.rust-lang.org/nightly/std/fs/fn.canonicalize.html) , [`str::MatchIndices`](http://doc.rust-lang.org/nightly/std/str/struct.MatchIndices.html) , [`str::RMatchIndices`](http://doc.rust-lang.org/nightly/std/str/struct.RMatchIndices.html) , [`str::match_indices`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.match_indices) , [`str::rmatch_indices`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.rmatch_indices) , [`str::slice_mut_unchecked`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.slice_mut_unchecked) , [`string::ParseError`](http://doc.rust-lang.org/nightly/std/string/enum.ParseError.html) . * Rust applications hosted on crates.io can be installed locally to `~/.cargo/bin` with the [`cargo install`](https://github.com/rust-lang/rfcs/blob/master/text/1200-cargo-install.md) command. Among other things this makes it easier to augment Cargo with new subcommands: when a binary named e.g. `cargo-foo` is found in `$PATH` it can be invoked as `cargo foo`. * Crates with wildcard (`*`) dependencies will [emit warnings when published](https://github.com/rust-lang/rfcs/blob/master/text/1241-no-wildcard-deps.md) . In 1.6 it will no longer be possible to publish crates with wildcard dependencies. [§](https://doc.rust-lang.org/stable/releases.html#breaking-changes) Breaking Changes ------------------------------------------------------------------------------------- * The rules determining when a particular lifetime must outlive a particular value (known as ‘[dropck](https://doc.rust-lang.org/nightly/nomicon/dropck.html) ’) have been [modified to not rely on parametricity](https://github.com/rust-lang/rfcs/blob/master/text/1238-nonparametric-dropck.md) . * [Implementations of `AsRef` and `AsMut` were added to `Box`, `Rc`, and `Arc`](https://github.com/rust-lang/rust/pull/28811) . Because these smart pointer types implement `Deref`, this causes breakage in cases where the interior type contains methods of the same name. * [Correct a bug in Rc/Arc](https://github.com/rust-lang/rust/pull/29110) that caused [dropck](https://doc.rust-lang.org/nightly/nomicon/dropck.html) to be unaware that they could drop their content. Soundness fix. * All method invocations are [properly checked](https://github.com/rust-lang/rust/pull/28669) for [well-formedness](https://github.com/rust-lang/rfcs/blob/master/text/1214-projections-lifetimes-and-wf.md) . Soundness fix. * Traits whose supertraits contain `Self` are [not object safe](https://github.com/rust-lang/rust/pull/29259) . Soundness fix. * Target specifications support a [`no_default_libraries`](https://github.com/rust-lang/rust/pull/28578) setting that controls whether `-nodefaultlibs` is passed to the linker, and in turn the `is_like_windows` setting no longer affects the `-nodefaultlibs` flag. * `#[derive(Show)]`, long-deprecated, [has been removed](https://github.com/rust-lang/rust/pull/29148) . * The `#[inline]` and `#[repr]` attributes [can only appear in valid locations](https://github.com/rust-lang/rust/pull/28650) . * Native libraries linked from the local crate are [passed to the linker before native libraries from upstream crates](https://github.com/rust-lang/rust/pull/28605) . * Two rarely-used attributes, `#[no_debug]` and `#[omit_gdb_pretty_printer_section]` [are feature gated](https://github.com/rust-lang/rust/pull/28522) . * Negation of unsigned integers, which has been a warning for several releases, [is now behind a feature gate and will generate errors](https://github.com/rust-lang/rust/pull/28468) . * The parser accidentally accepted visibility modifiers on enum variants, a bug [which has been fixed](https://github.com/rust-lang/rust/pull/28442) . * [A bug was fixed that allowed `use` statements to import unstable features](https://github.com/rust-lang/rust/pull/28364) . [§](https://doc.rust-lang.org/stable/releases.html#language-85) Language ------------------------------------------------------------------------ * When evaluating expressions at compile-time that are not compile-time constants (const-evaluating expressions in non-const contexts), incorrect code such as overlong bitshifts and arithmetic overflow will [generate a warning instead of an error](https://github.com/rust-lang/rfcs/blob/master/text/1229-compile-time-asserts.md) , delaying the error until runtime. This will allow the const-evaluator to be expanded in the future backwards-compatibly. * The `improper_ctypes` lint [no longer warns about using `isize` and `usize` in FFI](https://github.com/rust-lang/rust/pull/28779) . [§](https://doc.rust-lang.org/stable/releases.html#libraries-87) Libraries -------------------------------------------------------------------------- * `Arc` and `Rc` are [covariant with respect to `T` instead of invariant](https://github.com/rust-lang/rust/pull/29110) . * `Default` is [implemented for mutable slices](https://github.com/rust-lang/rust/pull/29245) . * `FromStr` is [implemented for `SockAddrV4` and `SockAddrV6`](https://github.com/rust-lang/rust/pull/29190) . * There are now `From` conversions [between floating point types](https://github.com/rust-lang/rust/pull/29129) where the conversions are lossless. * There are now `From` conversions [between integer types](https://github.com/rust-lang/rust/pull/28921) where the conversions are lossless. * [`fs::Metadata` implements `Clone`](https://github.com/rust-lang/rust/pull/29021) . * The `parse` method [accepts a leading “+” when parsing integers](https://github.com/rust-lang/rust/pull/28826) . * [`AsMut` is implemented for `Vec`](https://github.com/rust-lang/rust/pull/28663) . * The `clone_from` implementations for `String` and `BinaryHeap` [have been optimized](https://github.com/rust-lang/rust/pull/28602) and no longer rely on the default impl. * The `extern "Rust"`, `extern "C"`, `unsafe extern "Rust"` and `unsafe extern "C"` function types now [implement `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`, `fmt::Pointer`, and `fmt::Debug` for up to 12 arguments](https://github.com/rust-lang/rust/pull/28560) . * [Dropping `Vec`s is much faster in unoptimized builds when the element types don’t implement `Drop`](https://github.com/rust-lang/rust/pull/28531) . * A bug that caused in incorrect behavior when [combining `VecDeque` with zero-sized types](https://github.com/rust-lang/rust/pull/28494) was resolved. * [`PartialOrd` for slices is faster](https://github.com/rust-lang/rust/pull/28436) . [§](https://doc.rust-lang.org/stable/releases.html#miscellaneous) Miscellaneous ------------------------------------------------------------------------------- * [Crate metadata size was reduced by 20%](https://github.com/rust-lang/rust/pull/28521) . * [Improvements to code generation reduced the size of libcore by 3.3 MB and rustc’s memory usage by 18MB](https://github.com/rust-lang/rust/pull/28778) . * [Improvements to deref translation increased performance in unoptimized builds](https://github.com/rust-lang/rust/pull/28491) . * Various errors in trait resolution [are deduplicated to only be reported once](https://github.com/rust-lang/rust/pull/28645) . * Rust has preliminary [support for rumprun kernels](https://github.com/rust-lang/rust/pull/28593) . * Rust has preliminary [support for NetBSD on amd64](https://github.com/rust-lang/rust/pull/28543) . [§](https://doc.rust-lang.org/stable/releases.html#version-140-2015-10-29) Version 1.4.0 (2015-10-29) ===================================================================================================== * ~1200 changes, numerous bugfixes [§](https://doc.rust-lang.org/stable/releases.html#highlights-2) Highlights --------------------------------------------------------------------------- * Windows builds targeting the 64-bit MSVC ABI and linker (instead of GNU) are now supported and recommended for use. [§](https://doc.rust-lang.org/stable/releases.html#breaking-changes-1) Breaking Changes --------------------------------------------------------------------------------------- * [Several changes have been made to fix type soundness and improve the behavior of associated types](https://github.com/rust-lang/rust/pull/27641) . See [RFC 1214](https://github.com/rust-lang/rfcs/blob/master/text/1214-projections-lifetimes-and-wf.md) . Although we have mostly introduced these changes as warnings this release, to become errors next release, there are still some scenarios that will see immediate breakage. * [The `str::lines` and `BufRead::lines` iterators treat `\r\n` as line breaks in addition to `\n`](https://github.com/rust-lang/rust/pull/28034) . * [Loans of `'static` lifetime extend to the end of a function](https://github.com/rust-lang/rust/pull/28321) . * [`str::parse` no longer introduces avoidable rounding error when parsing floating point numbers. Together with earlier changes to float formatting/output, “round trips” like f.to\_string().parse() now preserve the value of f exactly. Additionally, leading plus signs are now accepted](https://github.com/rust-lang/rust/pull/27307) . [§](https://doc.rust-lang.org/stable/releases.html#language-86) Language ------------------------------------------------------------------------ * `use` statements that import multiple items [can now rename them](https://github.com/rust-lang/rust/pull/27451) , as in `use foo::{bar as kitten, baz as puppy}`. * [Binops work correctly on fat pointers](https://github.com/rust-lang/rust/pull/28270) . * `pub extern crate`, which does not behave as expected, [issues a warning](https://github.com/rust-lang/rust/pull/28486) until a better solution is found. [§](https://doc.rust-lang.org/stable/releases.html#libraries-88) Libraries -------------------------------------------------------------------------- * [Many APIs were stabilized](https://github.com/rust-lang/rust/pull/28339) : `>::into_string`, [`Arc::downgrade`](http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.downgrade) , [`Arc::get_mut`](http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.get_mut) , [`Arc::make_mut`](http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.make_mut) , [`Arc::try_unwrap`](http://doc.rust-lang.org/nightly/alloc/arc/struct.Arc.html#method.try_unwrap) , [`Box::from_raw`](http://doc.rust-lang.org/nightly/alloc/boxed/struct.Box.html#method.from_raw) , [`Box::into_raw`](http://doc.rust-lang.org/nightly/alloc/boxed/struct.Box.html#method.into_raw) , [`CStr::to_str`](http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html#method.to_str) , [`CStr::to_string_lossy`](http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html#method.to_string_lossy) , [`CString::from_raw`](http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.from_raw) , [`CString::into_raw`](http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_raw) , [`IntoRawFd::into_raw_fd`](http://doc.rust-lang.org/nightly/std/os/unix/io/trait.IntoRawFd.html#tymethod.into_raw_fd) , [`IntoRawFd`](http://doc.rust-lang.org/nightly/std/os/unix/io/trait.IntoRawFd.html) , `IntoRawHandle::into_raw_handle`, `IntoRawHandle`, `IntoRawSocket::into_raw_socket`, `IntoRawSocket`, [`Rc::downgrade`](http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.downgrade) , [`Rc::get_mut`](http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.get_mut) , [`Rc::make_mut`](http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.make_mut) , [`Rc::try_unwrap`](http://doc.rust-lang.org/nightly/alloc/rc/struct.Rc.html#method.try_unwrap) , [`Result::expect`](http://doc.rust-lang.org/nightly/core/result/enum.Result.html#method.expect) , [`String::into_boxed_str`](http://doc.rust-lang.org/nightly/collections/string/struct.String.html#method.into_boxed_str) , [`TcpStream::read_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.read_timeout) , [`TcpStream::set_read_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_read_timeout) , [`TcpStream::set_write_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_write_timeout) , [`TcpStream::write_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.write_timeout) , [`UdpSocket::read_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.read_timeout) , [`UdpSocket::set_read_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_read_timeout) , [`UdpSocket::set_write_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.set_write_timeout) , [`UdpSocket::write_timeout`](http://doc.rust-lang.org/nightly/std/net/struct.TcpStream.html#method.write_timeout) , `Vec::append`, `Vec::split_off`, [`VecDeque::append`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.append) , [`VecDeque::retain`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.retain) , [`VecDeque::split_off`](http://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.split_off) , [`rc::Weak::upgrade`](http://doc.rust-lang.org/nightly/std/rc/struct.Weak.html#method.upgrade) , [`rc::Weak`](http://doc.rust-lang.org/nightly/std/rc/struct.Weak.html) , [`slice::Iter::as_slice`](http://doc.rust-lang.org/nightly/std/slice/struct.Iter.html#method.as_slice) , [`slice::IterMut::into_slice`](http://doc.rust-lang.org/nightly/std/slice/struct.IterMut.html#method.into_slice) , [`str::CharIndices::as_str`](http://doc.rust-lang.org/nightly/std/str/struct.CharIndices.html#method.as_str) , [`str::Chars::as_str`](http://doc.rust-lang.org/nightly/std/str/struct.Chars.html#method.as_str) , [`str::split_at_mut`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_at_mut) , [`str::split_at`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_at) , [`sync::Weak::upgrade`](http://doc.rust-lang.org/nightly/std/sync/struct.Weak.html#method.upgrade) , [`sync::Weak`](http://doc.rust-lang.org/nightly/std/sync/struct.Weak.html) , [`thread::park_timeout`](http://doc.rust-lang.org/nightly/std/thread/fn.park_timeout.html) , [`thread::sleep`](http://doc.rust-lang.org/nightly/std/thread/fn.sleep.html) . * [Some APIs were deprecated](https://github.com/rust-lang/rust/pull/28339) : `BTreeMap::with_b`, `BTreeSet::with_b`, `Option::as_mut_slice`, `Option::as_slice`, `Result::as_mut_slice`, `Result::as_slice`, `f32::from_str_radix`, `f64::from_str_radix`. * [Reverse-searching strings is faster with the ‘two-way’ algorithm](https://github.com/rust-lang/rust/pull/27474) . * [`std::io::copy` allows `?Sized` arguments](https://github.com/rust-lang/rust/pull/27531) . * The `Windows`, `Chunks`, and `ChunksMut` iterators over slices all [override `count`, `nth` and `last` with an _O_(1) implementation](https://github.com/rust-lang/rust/pull/27652) . * [`Default` is implemented for arrays up to `[T; 32]`](https://github.com/rust-lang/rust/pull/27825) . * [`IntoRawFd` has been added to the Unix-specific prelude, `IntoRawSocket` and `IntoRawHandle` to the Windows-specific prelude](https://github.com/rust-lang/rust/pull/27896) . * [`Extend` and `FromIterator` where `T: Copy`](https://github.com/rust-lang/rust/pull/28094) as part of [RFC 839](https://github.com/rust-lang/rfcs/blob/master/text/0839-embrace-extend-extinguish.md) . This will cause type inference breakage in rare situations. * [`BinaryHeap` implements `Debug`](https://github.com/rust-lang/rust/pull/28156) . * [`Borrow` and `BorrowMut` are implemented for fixed-size arrays](https://github.com/rust-lang/rust/pull/28197) . * [`extern fn`s with the “Rust” and “C” ABIs implement common traits including `Eq`, `Ord`, `Debug`, `Hash`](https://github.com/rust-lang/rust/pull/28268) . * [String comparison is faster](https://github.com/rust-lang/rust/pull/28338) . * `&mut T` where `T: std::fmt::Write` [also implements `std::fmt::Write`](https://github.com/rust-lang/rust/pull/28368) . * [A stable regression in `VecDeque::push_back` and other capacity-altering methods that caused panics for zero-sized types was fixed](https://github.com/rust-lang/rust/pull/28494) . * [Function pointers implement traits for up to 12 parameters](https://github.com/rust-lang/rust/pull/28560) . [§](https://doc.rust-lang.org/stable/releases.html#miscellaneous-1) Miscellaneous --------------------------------------------------------------------------------- * The compiler [no longer uses the ‘morestack’ feature to prevent stack overflow](https://github.com/rust-lang/rust/pull/27338) . Instead it uses guard pages and stack probes (though stack probes are not yet implemented on any platform but Windows). * [The compiler matches traits faster when projections are involved](https://github.com/rust-lang/rust/pull/27866) . * The ‘improper\_ctypes’ lint [no longer warns about use of `isize` and `usize`](https://github.com/rust-lang/rust/pull/28779) . * [Cargo now displays useful information about what its doing during `cargo update`](https://github.com/rust-lang/cargo/pull/1931) . [§](https://doc.rust-lang.org/stable/releases.html#version-130-2015-09-17) Version 1.3.0 (2015-09-17) ===================================================================================================== * ~900 changes, numerous bugfixes [§](https://doc.rust-lang.org/stable/releases.html#highlights-3) Highlights --------------------------------------------------------------------------- * The [new object lifetime defaults](https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md) have been [turned on](https://github.com/rust-lang/rust/pull/27045) after a cycle of warnings about the change. Now types like `&'a Box` (or `&'a Rc`, etc) will change from being interpreted as `&'a Box` to `&'a Box`. * [The Rustonomicon](http://doc.rust-lang.org/nightly/nomicon/) is a new book in the official documentation that dives into writing unsafe Rust. * The [`Duration`](http://doc.rust-lang.org/nightly/std/time/struct.Duration.html) API, [has been stabilized](https://github.com/rust-lang/rust/pull/26818) . This basic unit of timekeeping is employed by other std APIs, as well as out-of-tree time crates. [§](https://doc.rust-lang.org/stable/releases.html#breaking-changes-2) Breaking Changes --------------------------------------------------------------------------------------- * The [new object lifetime defaults](https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md) have been [turned on](https://github.com/rust-lang/rust/pull/27045) after a cycle of warnings about the change. * There is a known [regression](https://github.com/rust-lang/rust/issues/27248) in how object lifetime elision is interpreted, the proper solution for which is undetermined. * The `#[prelude_import]` attribute, an internal implementation detail, was accidentally stabilized previously. [It has been put behind the `prelude_import` feature gate](https://github.com/rust-lang/rust/pull/26699) . This change is believed to break no existing code. * The behavior of [`size_of_val`](http://doc.rust-lang.org/nightly/std/mem/fn.size_of_val.html) and [`align_of_val`](http://doc.rust-lang.org/nightly/std/mem/fn.align_of_val.html) is [more sane for dynamically sized types](https://github.com/rust-lang/rust/pull/27351) . Code that relied on the previous behavior is thought to be broken. * The `dropck` rules, which checks that destructors can’t access destroyed values, [have been updated](https://doc.rust-lang.org/nightly/nomicon/dropck.html) to match the [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md) . This fixes some soundness holes, and as such will cause some previously-compiling code to no longer build. [§](https://doc.rust-lang.org/stable/releases.html#language-87) Language ------------------------------------------------------------------------ * The [new object lifetime defaults](https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md) have been [turned on](https://github.com/rust-lang/rust/pull/27045) after a cycle of warnings about the change. * Semicolons may [now follow types and paths in macros](https://github.com/rust-lang/rust/pull/27000) . * The behavior of [`size_of_val`](http://doc.rust-lang.org/nightly/std/mem/fn.size_of_val.html) and [`align_of_val`](http://doc.rust-lang.org/nightly/std/mem/fn.align_of_val.html) is [more sane for dynamically sized types](https://github.com/rust-lang/rust/pull/27351) . Code that relied on the previous behavior is not known to exist, and suspected to be broken. * `'static` variables [may now be recursive](https://github.com/rust-lang/rust/pull/26630) . * `ref` bindings choose between [`Deref`](http://doc.rust-lang.org/nightly/std/ops/trait.Deref.html) and [`DerefMut`](http://doc.rust-lang.org/nightly/std/ops/trait.DerefMut.html) implementations correctly. * The `dropck` rules, which checks that destructors can’t access destroyed values, [have been updated](https://doc.rust-lang.org/nightly/nomicon/dropck.html) to match the [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md) . [§](https://doc.rust-lang.org/stable/releases.html#libraries-89) Libraries -------------------------------------------------------------------------- * The [`Duration`](http://doc.rust-lang.org/nightly/std/time/struct.Duration.html) API, [has been stabilized](https://github.com/rust-lang/rust/pull/26818) , as well as the `std::time` module, which presently contains only `Duration`. * `Box` and `Box<[T]>` both implement `Clone`. * The owned C string, [`CString`](http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html) , implements [`Borrow`](http://doc.rust-lang.org/nightly/std/borrow/trait.Borrow.html) and the borrowed C string, [`CStr`](http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html) , implements [`ToOwned`](http://doc.rust-lang.org/nightly/std/borrow/trait.ToOwned.html) . The two of these allow C strings to be borrowed and cloned in generic code. * [`CStr`](http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html) implements [`Debug`](http://doc.rust-lang.org/nightly/std/fmt/trait.Debug.html) . * [`AtomicPtr`](http://doc.rust-lang.org/nightly/std/sync/atomic/struct.AtomicPtr.html) implements [`Debug`](http://doc.rust-lang.org/nightly/std/fmt/trait.Debug.html) . * [`Error`](http://doc.rust-lang.org/nightly/std/error/trait.Error.html) trait objects [can be downcast to their concrete types](https://github.com/rust-lang/rust/pull/24793) in many common configurations, using the [`is`](http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.is) , [`downcast`](http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast) , [`downcast_ref`](http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast_ref) and [`downcast_mut`](http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast_mut) methods, similarly to the [`Any`](http://doc.rust-lang.org/nightly/std/any/trait.Any.html) trait. * Searching for substrings now [employs the two-way algorithm](https://github.com/rust-lang/rust/pull/26327) instead of doing a naive search. This gives major speedups to a number of methods, including [`contains`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.contains) , [`find`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.find) , [`rfind`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.rfind) , [`split`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split) . [`starts_with`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.starts_with) and [`ends_with`](http://doc.rust-lang.org/nightly/std/primitive.str.html#method.ends_with) are also faster. * The performance of `PartialEq` for slices is [much faster](https://github.com/rust-lang/rust/pull/26884) . * The [`Hash`](http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html) trait offers the default method, [`hash_slice`](http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html#method.hash_slice) , which is overridden and optimized by the implementations for scalars. * The [`Hasher`](http://doc.rust-lang.org/nightly/std/hash/trait.Hasher.html) trait now has a number of specialized `write_*` methods for primitive types, for efficiency. * The I/O-specific error type, [`std::io::Error`](http://doc.rust-lang.org/nightly/std/io/struct.Error.html) , gained a set of methods for accessing the ‘inner error’, if any: [`get_ref`](http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.get_ref) , [`get_mut`](http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.get_mut) , [`into_inner`](http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.into_inner) . As well, the implementation of [`std::error::Error::cause`](http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.cause) also delegates to the inner error. * [`process::Child`](http://doc.rust-lang.org/nightly/std/process/struct.Child.html) gained the [`id`](http://doc.rust-lang.org/nightly/std/process/struct.Child.html#method.id) method, which returns a `u32` representing the platform-specific process identifier. * The [`connect`](http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html#method.connect) method on slices is deprecated, replaced by the new [`join`](http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html#method.join) method (note that both of these are on the _unstable_ [`SliceConcatExt`](http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html) trait, but through the magic of the prelude are available to stable code anyway). * The [`Div`](http://doc.rust-lang.org/nightly/std/ops/trait.Div.html) operator is implemented for [`Wrapping`](http://doc.rust-lang.org/nightly/std/num/struct.Wrapping.html) types. * [`DerefMut` is implemented for `String`](https://github.com/rust-lang/rust/pull/26241) . * Performance of SipHash (the default hasher for `HashMap`) is [better for long data](https://github.com/rust-lang/rust/pull/27280) . * [`AtomicPtr`](http://doc.rust-lang.org/nightly/std/sync/atomic/struct.AtomicPtr.html) implements [`Send`](http://doc.rust-lang.org/nightly/std/marker/trait.Send.html) . * The [`read_to_end`](http://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end) implementations for [`Stdin`](http://doc.rust-lang.org/nightly/std/io/struct.Stdin.html) and [`File`](http://doc.rust-lang.org/nightly/std/fs/struct.File.html) are now [specialized to use uninitialized buffers for increased performance](https://github.com/rust-lang/rust/pull/26950) . * Lifetime parameters of foreign functions [are now resolved properly](https://github.com/rust-lang/rust/pull/26588) . [§](https://doc.rust-lang.org/stable/releases.html#misc-48) Misc ---------------------------------------------------------------- * Rust can now, with some coercion, [produce programs that run on Windows XP](https://github.com/rust-lang/rust/pull/26569) , though XP is not considered a supported platform. * Porting Rust on Windows from the GNU toolchain to MSVC continues ([1](https://github.com/rust-lang/rust/pull/26569) , [2](https://github.com/rust-lang/rust/pull/26741) , [3](https://github.com/rust-lang/rust/pull/26741) , [4](https://github.com/rust-lang/rust/pull/27210) ). It is still not recommended for use in 1.3, though should be fully-functional in the [64-bit 1.4 beta](https://static.rust-lang.org/dist/rust-beta-x86_64-pc-windows-msvc.msi) . * On Fedora-based systems installation will [properly configure the dynamic linker](https://github.com/rust-lang/rust-installer/pull/41) . * The compiler gained many new extended error descriptions, which can be accessed with the `--explain` flag. * The `dropck` pass, which checks that destructors can’t access destroyed values, [has been rewritten](https://github.com/rust-lang/rust/pull/27261) . This fixes some soundness holes, and as such will cause some previously-compiling code to no longer build. * `rustc` now uses [LLVM to write archive files where possible](https://github.com/rust-lang/rust/pull/26926) . Eventually this will eliminate the compiler’s dependency on the ar utility. * Rust has [preliminary support for i686 FreeBSD](https://github.com/rust-lang/rust/pull/26959) (it has long supported FreeBSD on x86\_64). * The [`unused_mut`](https://github.com/rust-lang/rust/pull/26378) , [`unconditional_recursion`](https://github.com/rust-lang/rust/pull/26783) , [`improper_ctypes`](https://github.com/rust-lang/rust/pull/26583) , and [`negate_unsigned`](https://github.com/rust-lang/rust/pull/27026) lints are more strict. * If landing pads are disabled (with `-Z no-landing-pads`), [`panic!` will kill the process instead of leaking](https://github.com/rust-lang/rust/pull/27176) . [§](https://doc.rust-lang.org/stable/releases.html#version-120-2015-08-07) Version 1.2.0 (2015-08-07) ===================================================================================================== * ~1200 changes, numerous bugfixes [§](https://doc.rust-lang.org/stable/releases.html#highlights-4) Highlights --------------------------------------------------------------------------- * [Dynamically-sized-type coercions](https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md) allow smart pointer types like `Rc` to contain types without a fixed size, arrays and trait objects, finally enabling use of `Rc<[T]>` and completing the implementation of DST. * [Parallel codegen](https://github.com/rust-lang/rust/pull/26018) is now working again, which can substantially speed up large builds in debug mode; It also gets another ~33% speedup when bootstrapping on a 4 core machine (using 8 jobs). It’s not enabled by default, but will be “in the near future”. It can be activated with the `-C codegen-units=N` flag to `rustc`. * This is the first release with [experimental support for linking with the MSVC linker and lib C on Windows (instead of using the GNU variants via MinGW)](https://github.com/rust-lang/rust/pull/25350) . It is yet recommended only for the most intrepid Rustaceans. * Benchmark compilations are showing a 30% improvement in bootstrapping over 1.1. [§](https://doc.rust-lang.org/stable/releases.html#breaking-changes-3) Breaking Changes --------------------------------------------------------------------------------------- * The [`to_uppercase`](https://doc.rust-lang.org/nightly/std/primitive.char.html#method.to_uppercase) and [`to_lowercase`](https://doc.rust-lang.org/nightly/std/primitive.char.html#method.to_lowercase) methods on `char` now do unicode case mapping, which is a previously-planned change in behavior and considered a bugfix. * [`mem::align_of`](https://doc.rust-lang.org/nightly/std/mem/fn.align_of.html) now specifies [the _minimum alignment_ for T](https://github.com/rust-lang/rust/pull/25646) , which is usually the alignment programs are interested in, and the same value reported by clang’s `alignof`. [`mem::min_align_of`](https://doc.rust-lang.org/nightly/std/mem/fn.min_align_of.html) is deprecated. This is not known to break real code. * [The `#[packed]` attribute is no longer silently accepted by the compiler](https://github.com/rust-lang/rust/pull/25541) . This attribute did nothing and code that mentioned it likely did not work as intended. * Associated type defaults are [now behind the `associated_type_defaults` feature gate](https://github.com/rust-lang/rust/pull/27382) . In 1.1 associated type defaults _did not work_, but could be mentioned syntactically. As such this breakage has minimal impact. [§](https://doc.rust-lang.org/stable/releases.html#language-88) Language ------------------------------------------------------------------------ * Patterns with `ref mut` now correctly invoke [`DerefMut`](http://doc.rust-lang.org/nightly/std/ops/trait.DerefMut.html) when matching against dereferenceable values. [§](https://doc.rust-lang.org/stable/releases.html#libraries-90) Libraries -------------------------------------------------------------------------- * The [`Extend`](https://doc.rust-lang.org/nightly/std/iter/trait.Extend.html) trait, which grows a collection from an iterator, is implemented over iterators of references, for `String`, `Vec`, `LinkedList`, `VecDeque`, `EnumSet`, `BinaryHeap`, `VecMap`, `BTreeSet` and `BTreeMap`. [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0839-embrace-extend-extinguish.md) . * The [`iter::once`](https://doc.rust-lang.org/nightly/std/iter/fn.once.html) function returns an iterator that yields a single element, and [`iter::empty`](https://doc.rust-lang.org/std/iter/fn.empty.html) returns an iterator that yields no elements. * The [`matches`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.matches) and [`rmatches`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.rmatches) methods on `str` return iterators over substring matches. * [`Cell`](https://doc.rust-lang.org/nightly/std/cell/struct.Cell.html) and [`RefCell`](https://doc.rust-lang.org/nightly/std/cell/struct.RefCell.html) both implement `Eq`. * A number of methods for wrapping arithmetic are added to the integral types, [`wrapping_div`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_div) , [`wrapping_rem`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_rem) , [`wrapping_neg`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_neg) , [`wrapping_shl`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_shl) , [`wrapping_shr`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_shr) . These are in addition to the existing [`wrapping_add`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_add) , [`wrapping_sub`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_sub) , and [`wrapping_mul`](https://doc.rust-lang.org/nightly/std/primitive.i8.html#method.wrapping_mul) methods, and alternatives to the [`Wrapping`](http://doc.rust-lang.org/nightly/std/num/struct.Wrapping.html) type.. It is illegal for the default arithmetic operations in Rust to overflow; the desire to wrap must be explicit. * The `{:#?}` formatting specifier [displays the alternate, pretty-printed](https://www.reddit.com/r/rust/comments/3ceaui/psa_produces_prettyprinted_debug_output/) form of the `Debug` formatter. This feature was actually introduced prior to 1.0 with little fanfare. * [`fmt::Formatter`](https://doc.rust-lang.org/nightly/std/fmt/struct.Formatter.html) implements [`fmt::Write`](https://doc.rust-lang.org/nightly/std/fmt/trait.Write.html) , a `fmt`\-specific trait for writing data to formatted strings, similar to [`io::Write`](https://doc.rust-lang.org/nightly/std/io/trait.Write.html) . * [`fmt::Formatter`](https://doc.rust-lang.org/nightly/std/fmt/struct.Formatter.html) adds ‘debug builder’ methods, [`debug_struct`](https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_struct) , [`debug_tuple`](https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_tuple) , [`debug_list`](https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_list) , [`debug_set`](https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_set) , [`debug_map`](https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html#method.debug_map) . These are used by code generators to emit implementations of [`Debug`](http://doc.rust-lang.org/nightly/std/fmt/trait.Debug.html) . * `str` has new [`to_uppercase`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.to_uppercase) and [`to_lowercase`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.to_lowercase) methods that convert case, following Unicode case mapping. * It is now easier to handle poisoned locks. The [`PoisonError`](https://doc.rust-lang.org/nightly/std/sync/struct.PoisonError.html) type, returned by failing lock operations, exposes `into_inner`, `get_ref`, and `get_mut`, which all give access to the inner lock guard, and allow the poisoned lock to continue to operate. The `is_poisoned` method of [`RwLock`](https://doc.rust-lang.org/nightly/std/sync/struct.RwLock.html) and [`Mutex`](https://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html) can poll for a poisoned lock without attempting to take the lock. * On Unix the [`FromRawFd`](https://doc.rust-lang.org/nightly/std/os/unix/io/trait.FromRawFd.html) trait is implemented for [`Stdio`](https://doc.rust-lang.org/nightly/std/process/struct.Stdio.html) , and [`AsRawFd`](https://doc.rust-lang.org/nightly/std/os/unix/io/trait.AsRawFd.html) for [`ChildStdin`](https://doc.rust-lang.org/nightly/std/process/struct.ChildStdin.html) , [`ChildStdout`](https://doc.rust-lang.org/nightly/std/process/struct.ChildStdout.html) , [`ChildStderr`](https://doc.rust-lang.org/nightly/std/process/struct.ChildStderr.html) . On Windows the `FromRawHandle` trait is implemented for `Stdio`, and `AsRawHandle` for `ChildStdin`, `ChildStdout`, `ChildStderr`. * [`io::ErrorKind`](https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html) has a new variant, `InvalidData`, which indicates malformed input. [§](https://doc.rust-lang.org/stable/releases.html#misc-49) Misc ---------------------------------------------------------------- * `rustc` employs smarter heuristics for guessing at [typos](https://github.com/rust-lang/rust/pull/26087) . * `rustc` emits more efficient code for [no-op conversions between unsafe pointers](https://github.com/rust-lang/rust/pull/26336) . * Fat pointers are now [passed in pairs of immediate arguments](https://github.com/rust-lang/rust/pull/26411) , resulting in faster compile times and smaller code. [§](https://doc.rust-lang.org/stable/releases.html#version-110-2015-06-25) Version 1.1.0 (2015-06-25) ===================================================================================================== * ~850 changes, numerous bugfixes [§](https://doc.rust-lang.org/stable/releases.html#highlights-5) Highlights --------------------------------------------------------------------------- * The [`std::fs` module has been expanded](https://github.com/rust-lang/rfcs/blob/master/text/1044-io-fs-2.1.md) to expand the set of functionality exposed: * `DirEntry` now supports optimizations like `file_type` and `metadata` which don’t incur a syscall on some platforms. * A `symlink_metadata` function has been added. * The `fs::Metadata` structure now lowers to its OS counterpart, providing access to all underlying information. * The compiler now contains extended explanations of many errors. When an error with an explanation occurs the compiler suggests using the `--explain` flag to read the explanation. Error explanations are also [available online](https://doc.rust-lang.org/error-index.html) . * Thanks to multiple [improvements](https://github.com/rust-lang/rust/pull/24615) to [type checking](https://github.com/rust-lang/rust/pull/25323) , as well as other work, the time to bootstrap the compiler decreased by 32%. [§](https://doc.rust-lang.org/stable/releases.html#libraries-91) Libraries -------------------------------------------------------------------------- * The [`str::split_whitespace`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_whitespace) method splits a string on unicode whitespace boundaries. * On both Windows and Unix, new extension traits provide conversion of I/O types to and from the underlying system handles. On Unix, these traits are [`FromRawFd`](https://doc.rust-lang.org/nightly/std/os/unix/io/trait.FromRawFd.html) and [`AsRawFd`](https://doc.rust-lang.org/nightly/std/os/unix/io/trait.AsRawFd.html) , on Windows `FromRawHandle` and `AsRawHandle`. These are implemented for `File`, `TcpStream`, `TcpListener`, and `UpdSocket`. Further implementations for `std::process` will be stabilized later. * On Unix, [`std::os::unix::symlink`](https://doc.rust-lang.org/nightly/std/os/unix/fs/fn.symlink.html) creates symlinks. On Windows, symlinks can be created with `std::os::windows::symlink_dir` and `std::os::windows::symlink_file`. * The `mpsc::Receiver` type can now be converted into an iterator with `into_iter` on the [`IntoIterator`](https://doc.rust-lang.org/nightly/std/iter/trait.IntoIterator.html) trait. * `Ipv4Addr` can be created from `u32` with the `From` implementation of the [`From`](https://doc.rust-lang.org/nightly/std/convert/trait.From.html) trait. * The `Debug` implementation for `RangeFull` [creates output that is more consistent with other implementations](https://github.com/rust-lang/rust/pull/24491) . * [`Debug` is implemented for `File`](https://github.com/rust-lang/rust/pull/24598) . * The `Default` implementation for `Arc` [no longer requires `Sync + Send`](https://github.com/rust-lang/rust/pull/24695) . * [The `Iterator` methods `count`, `nth`, and `last` have been overridden for slices to have _O_(1) performance instead of _O_(_n_)](https://github.com/rust-lang/rust/pull/24701) . * Incorrect handling of paths on Windows has been improved in both the compiler and the standard library. * [`AtomicPtr` gained a `Default` implementation](https://github.com/rust-lang/rust/pull/24834) . * In accordance with Rust’s policy on arithmetic overflow `abs` now [panics on overflow when debug assertions are enabled](https://github.com/rust-lang/rust/pull/25441) . * The [`Cloned`](https://doc.rust-lang.org/nightly/std/iter/struct.Cloned.html) iterator, which was accidentally left unstable for 1.0 [has been stabilized](https://github.com/rust-lang/rust/pull/25496) . * The [`Incoming`](https://doc.rust-lang.org/nightly/std/net/struct.Incoming.html) iterator, which iterates over incoming TCP connections, and which was accidentally unnamable in 1.0, [is now properly exported](https://github.com/rust-lang/rust/pull/25522) . * [`BinaryHeap`](https://doc.rust-lang.org/nightly/std/collections/struct.BinaryHeap.html) no longer corrupts itself [when functions called by `sift_up` or `sift_down` panic](https://github.com/rust-lang/rust/pull/25856) . * The [`split_off`](https://doc.rust-lang.org/nightly/collections/linked_list/struct.LinkedList.html#method.split_off) method of `LinkedList` [no longer corrupts the list in certain scenarios](https://github.com/rust-lang/rust/pull/26022) . [§](https://doc.rust-lang.org/stable/releases.html#misc-50) Misc ---------------------------------------------------------------- * Type checking performance [has improved notably](https://github.com/rust-lang/rust/pull/24615) with [multiple improvements](https://github.com/rust-lang/rust/pull/25323) . * The compiler [suggests code changes](https://github.com/rust-lang/rust/pull/24683) for more errors. * rustc and it’s build system have experimental support for [building toolchains against MUSL](https://github.com/rust-lang/rust/pull/24777) instead of glibc on Linux. * The compiler defines the `target_env` cfg value, which is used for distinguishing toolchains that are otherwise for the same platform. Presently this is set to `gnu` for common GNU Linux targets and for MinGW targets, and `musl` for MUSL Linux targets. * The [`cargo rustc`](https://github.com/rust-lang/cargo/pull/1568) command invokes a build with custom flags to rustc. * [Android executables are always position independent](https://github.com/rust-lang/rust/pull/24953) . * [The `drop_with_repr_extern` lint warns about mixing `repr(C)` with `Drop`](https://github.com/rust-lang/rust/pull/24935) . [§](https://doc.rust-lang.org/stable/releases.html#version-100-2015-05-15) Version 1.0.0 (2015-05-15) ===================================================================================================== * ~1500 changes, numerous bugfixes [§](https://doc.rust-lang.org/stable/releases.html#highlights-6) Highlights --------------------------------------------------------------------------- * The vast majority of the standard library is now `#[stable]`. It is no longer possible to use unstable features with a stable build of the compiler. * Many popular crates on [crates.io](http://crates.io/) now work on the stable release channel. * Arithmetic on basic integer types now [checks for overflow in debug builds](https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md) . [§](https://doc.rust-lang.org/stable/releases.html#language-89) Language ------------------------------------------------------------------------ * Several [restrictions have been added to trait coherence](https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md) in order to make it easier for upstream authors to change traits without breaking downstream code. * Digits of binary and octal literals are [lexed more eagerly](https://github.com/rust-lang/rfcs/blob/master/text/0879-small-base-lexing.md) to improve error messages and macro behavior. For example, `0b1234` is now lexed as `0b1234` instead of two tokens, `0b1` and `234`. * Trait bounds [are always invariant](https://github.com/rust-lang/rust/pull/23938) , eliminating the need for the `PhantomFn` and `MarkerTrait` lang items, which have been removed. * [“-” is no longer a valid character in crate names](https://github.com/rust-lang/rust/pull/23419) , the `extern crate "foo" as bar` syntax has been replaced with `extern crate foo as bar`, and Cargo now automatically translates “-” in _package_ names to underscore for the crate name. * [Lifetime shadowing is an error](https://github.com/rust-lang/rust/pull/24057) . * [`Send` no longer implies `'static`](https://github.com/rust-lang/rfcs/blob/master/text/0458-send-improvements.md) . * [UFCS now supports trait-less associated paths](https://github.com/rust-lang/rust/pull/22172) like `MyType::default()`. * Primitive types [now have inherent methods](https://github.com/rust-lang/rust/pull/23104) , obviating the need for extension traits like `SliceExt`. * Methods with `Self: Sized` in their `where` clause are [considered object-safe](https://github.com/rust-lang/rust/pull/22301) , allowing many extension traits like `IteratorExt` to be merged into the traits they extended. * You can now [refer to associated types](https://github.com/rust-lang/rust/pull/22512) whose corresponding trait bounds appear only in a `where` clause. * The final bits of [OIBIT landed](https://github.com/rust-lang/rust/pull/21689) , meaning that traits like `Send` and `Sync` are now library-defined. * A [Reflect trait](https://github.com/rust-lang/rust/pull/23712) was introduced, which means that downcasting via the `Any` trait is effectively limited to concrete types. This helps retain the potentially-important “parametricity” property: generic code cannot behave differently for different type arguments except in minor ways. * The `unsafe_destructor` feature is now deprecated in favor of the [new `dropck`](https://github.com/rust-lang/rfcs/pull/769) . This change is a major reduction in unsafe code. [§](https://doc.rust-lang.org/stable/releases.html#libraries-92) Libraries -------------------------------------------------------------------------- * The `thread_local` module [has been renamed to `std::thread`](https://github.com/rust-lang/rfcs/blob/master/text/0909-move-thread-local-to-std-thread.md) . * The methods of `IteratorExt` [have been moved to the `Iterator` trait itself](https://github.com/rust-lang/rust/pull/23300) . * Several traits that implement Rust’s conventions for type conversions, `AsMut`, `AsRef`, `From`, and `Into` have been [centralized in the `std::convert` module](https://github.com/rust-lang/rust/pull/23875) . * The `FromError` trait [was removed in favor of `From`](https://github.com/rust-lang/rust/pull/23879) . * The basic sleep function [has moved to `std::thread::sleep_ms`](https://github.com/rust-lang/rust/pull/23949) . * The `splitn` function now takes an `n` parameter that represents the number of items yielded by the returned iterator [instead of the number of ‘splits’](https://github.com/rust-lang/rfcs/blob/master/text/0979-align-splitn-with-other-languages.md) . * [On Unix, all file descriptors are `CLOEXEC` by default](https://github.com/rust-lang/rust/pull/24034) . * [Derived implementations of `PartialOrd` now order enums according to their explicitly-assigned discriminants](https://github.com/rust-lang/rust/pull/24270) . * [Methods for searching strings are generic over `Pattern`s](https://github.com/rust-lang/rfcs/blob/master/text/0528-string-patterns.md) , implemented presently by `&char`, `&str`, `FnMut(char) -> bool` and some others. * [In method resolution, object methods are resolved before inherent methods](https://github.com/rust-lang/rust/pull/24056) . * [`String::from_str` has been deprecated in favor of the `From` impl, `String::from`](https://github.com/rust-lang/rust/pull/24517) . * [`io::Error` implements `Sync`](https://github.com/rust-lang/rust/pull/24133) . * [The `words` method on `&str` has been replaced with `split_whitespace`](https://github.com/rust-lang/rfcs/blob/master/text/1054-str-words.md) , to avoid answering the tricky question, ‘what is a word?’ * The new path and IO modules are complete and `#[stable]`. This was the major library focus for this cycle. * The path API was [revised](https://github.com/rust-lang/rust/pull/23229) to normalize `.`, adjusting the tradeoffs in favor of the most common usage. * A large number of remaining APIs in `std` were also stabilized during this cycle; about 75% of the non-deprecated API surface is now stable. * The new [string pattern API](https://github.com/rust-lang/rust/pull/22466) landed, which makes the string slice API much more internally consistent and flexible. * A new set of [generic conversion traits](https://github.com/rust-lang/rfcs/pull/529) replaced many existing ad hoc traits. * Generic numeric traits were [completely removed](https://github.com/rust-lang/rust/pull/23549) . This was made possible thanks to inherent methods for primitive types, and the removal gives maximal flexibility for designing a numeric hierarchy in the future. * The `Fn` traits are now related via [inheritance](https://github.com/rust-lang/rust/pull/23282) and provide ergonomic [blanket implementations](https://github.com/rust-lang/rust/pull/23895) . * The `Index` and `IndexMut` traits were changed to [take the index by value](https://github.com/rust-lang/rust/pull/23601) , enabling code like `hash_map["string"]` to work. * `Copy` now [inherits](https://github.com/rust-lang/rust/pull/23860) from `Clone`, meaning that all `Copy` data is known to be `Clone` as well. [§](https://doc.rust-lang.org/stable/releases.html#misc-51) Misc ---------------------------------------------------------------- * Many errors now have extended explanations that can be accessed with the `--explain` flag to `rustc`. * Many new examples have been added to the standard library documentation. * rustdoc has received a number of improvements focused on completion and polish. * Metadata was tuned, shrinking binaries [by 27%](https://github.com/rust-lang/rust/pull/22971) . * Much headway was made on ecosystem-wide CI, making it possible to [compare builds for breakage](https://gist.github.com/brson/a30a77836fbec057cbee) . [§](https://doc.rust-lang.org/stable/releases.html#version-100-alpha2-2015-02-20) Version 1.0.0-alpha.2 (2015-02-20) ==================================================================================================================== * ~1300 changes, numerous bugfixes * Highlights * The various I/O modules were [overhauled](https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md) to reduce unnecessary abstractions and provide better interoperation with the underlying platform. The old `io` module remains temporarily at `std::old_io`. * The standard library now [participates in feature gating](https://github.com/rust-lang/rust/pull/21248) , so use of unstable libraries now requires a `#![feature(...)]` attribute. The impact of this change is [described on the forum](https://users.rust-lang.org/t/psa-important-info-about-rustcs-new-feature-staging/82/5) . [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0507-release-channels.md) . * Language * `for` loops [now operate on the `IntoIterator` trait](https://github.com/rust-lang/rust/pull/20790) , which eliminates the need to call `.iter()`, etc. to iterate over collections. There are some new subtleties to remember though regarding what sort of iterators various types yield, in particular that `for foo in bar { }` yields values from a move iterator, destroying the original collection. [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0235-collections-conventions.md#intoiterator-and-iterable) . * Objects now have [default lifetime bounds](https://github.com/rust-lang/rust/pull/22230) , so you don’t have to write `Box` when you don’t care about storing references. [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md) . * In types that implement `Drop`, [lifetimes must outlive the value](https://github.com/rust-lang/rust/pull/21972) . This will soon make it possible to safely implement `Drop` for types where `#[unsafe_destructor]` is now required. Read the [gorgeous RFC](https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md) for details. * The fully qualified ::X syntax lets you set the Self type for a trait method or associated type. [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md) . * References to types that implement `Deref` now [automatically coerce to references](https://github.com/rust-lang/rust/pull/21351) to the dereferenced type `U`, e.g. `&T where T: Deref` automatically coerces to `&U`. This should eliminate many unsightly uses of `&*`, as when converting from references to vectors into references to slices. [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0241-deref-conversions.md) . * The explicit [closure kind syntax](https://github.com/rust-lang/rust/pull/21843) (`|&:|`, `|&mut:|`, `|:|`) is obsolete and closure kind is inferred from context. * [`Self` is a keyword](https://github.com/rust-lang/rust/pull/22158) . * Libraries * The `Show` and `String` formatting traits [have been renamed](https://github.com/rust-lang/rust/pull/21457) to `Debug` and `Display` to more clearly reflect their related purposes. Automatically getting a string conversion to use with `format!("{:?}", something_to_debug)` is now written `#[derive(Debug)]`. * Abstract [OS-specific string types](https://github.com/rust-lang/rust/pull/21488) , `std::ff::{OsString, OsStr}`, provide strings in platform-specific encodings for easier interop with system APIs. [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md) . * The `boxed::into_raw` and `Box::from_raw` functions [convert between `Box` and `*mut T`](https://github.com/rust-lang/rust/pull/21318) , a common pattern for creating raw pointers. * Tooling * Certain long error messages of the form ‘expected foo found bar’ are now [split neatly across multiple lines](https://github.com/rust-lang/rust/pull/19870) . Examples in the PR. * On Unix Rust can be [uninstalled](https://github.com/rust-lang/rust/pull/22256) by running `/usr/local/lib/rustlib/uninstall.sh`. * The `#[rustc_on_unimplemented]` attribute, requiring the ‘on\_unimplemented’ feature, lets rustc [display custom error messages when a trait is expected to be implemented for a type but is not](https://github.com/rust-lang/rust/pull/20889) . * Misc * Rust is tested against a [LALR grammar](https://github.com/rust-lang/rust/pull/21452) , which parses almost all the Rust files that rustc does. [§](https://doc.rust-lang.org/stable/releases.html#version-100-alpha-2015-01-09) Version 1.0.0-alpha (2015-01-09) ================================================================================================================= * ~2400 changes, numerous bugfixes * Highlights * The language itself is considered feature complete for 1.0, though there will be many usability improvements and bugfixes before the final release. * Nearly 50% of the public API surface of the standard library has been declared ‘stable’. Those interfaces are unlikely to change before 1.0. * The long-running debate over integer types has been [settled](https://github.com/rust-lang/rfcs/pull/544#issuecomment-68760871) : Rust will ship with types named `isize` and `usize`, rather than `int` and `uint`, for pointer-sized integers. Guidelines will be rolled out during the alpha cycle. * Most crates that are not `std` have been moved out of the Rust distribution into the Cargo ecosystem so they can evolve separately and don’t need to be stabilized as quickly, including ‘time’, ‘getopts’, ‘num’, ‘regex’, and ‘term’. * Documentation continues to be expanded with more API coverage, more examples, and more in-depth explanations. The guides have been consolidated into [The Rust Programming Language](https://doc.rust-lang.org/book/index.html) . * “[Rust By Example](http://rustbyexample.com/) ” is now maintained by the Rust team. * All official Rust binary installers now come with [Cargo](https://crates.io/) , the Rust package manager. * Language * Closures have been [completely redesigned](http://smallcultfollowing.com/babysteps/blog/2014/11/26/purging-proc/) to be implemented in terms of traits, can now be used as generic type bounds and thus monomorphized and inlined, or via an opaque pointer (boxed) as in the old system. The new system is often referred to as ‘unboxed’ closures. * Traits now support [associated types](https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md) , allowing families of related types to be defined together and used generically in powerful ways. * Enum variants are [namespaced by their type names](https://github.com/rust-lang/rfcs/blob/master/text/0390-enum-namespacing.md) . * [`where` clauses](https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md) provide a more versatile and attractive syntax for specifying generic bounds, though the previous syntax remains valid. * Rust again picks a [fallback](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) (either i32 or f64) for uninferred numeric types. * Rust [no longer has a runtime](https://github.com/rust-lang/rfcs/blob/master/text/0230-remove-runtime.md) of any description, and only supports OS threads, not green threads. * At long last, Rust has been overhauled for ‘dynamically-sized types’ ([DST](https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md) ), which integrates ‘fat pointers’ (object types, arrays, and `str`) more deeply into the type system, making it more consistent. * Rust now has a general [range syntax](https://github.com/rust-lang/rfcs/blob/master/text/0439-cmp-ops-reform.md#indexing-and-slicing) , `i..j`, `i..`, and `..j` that produce range types and which, when combined with the `Index` operator and multidispatch, leads to a convenient slice notation, `[i..j]`. * The new range syntax revealed an ambiguity in the fixed-length array syntax, so now fixed length arrays [are written `[T; N]`](https://github.com/rust-lang/rfcs/blob/master/text/0520-new-array-repeat-syntax.md) . * The `Copy` trait is no longer implemented automatically. Unsafe pointers no longer implement `Sync` and `Send` so types containing them don’t automatically either. `Sync` and `Send` are now ‘unsafe traits’ so one can “forcibly” implement them via `unsafe impl` if a type confirms to the requirements for them even though the internals do not (e.g. structs containing unsafe pointers like `Arc`). These changes are intended to prevent some footguns and are collectively known as [opt-in built-in traits](https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md) (though `Sync` and `Send` will soon become pure library types unknown to the compiler). * Operator traits now take their operands [by value](https://github.com/rust-lang/rfcs/blob/master/text/0439-cmp-ops-reform.md) , and comparison traits can use multidispatch to compare one type against multiple other types, allowing e.g. `String` to be compared with `&str`. * `if let` and `while let` are no longer feature-gated. * Rust has adopted a more [uniform syntax for escaping unicode characters](https://github.com/rust-lang/rfcs/blob/master/text/0446-es6-unicode-escapes.md) . * `macro_rules!` [has been declared stable](https://github.com/rust-lang/rfcs/blob/master/text/0453-macro-reform.md) . Though it is a flawed system it is sufficiently popular that it must be usable for 1.0. Effort has gone into [future-proofing](https://github.com/rust-lang/rfcs/pull/550) it in ways that will allow other macro systems to be developed in parallel, and won’t otherwise impact the evolution of the language. * The prelude has been [pared back significantly](https://github.com/rust-lang/rfcs/blob/master/text/0503-prelude-stabilization.md) such that it is the minimum necessary to support the most pervasive code patterns, and through [generalized where clauses](https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md) many of the prelude extension traits have been consolidated. * Rust’s rudimentary reflection [has been removed](https://github.com/rust-lang/rfcs/blob/master/text/0379-remove-reflection.md) , as it incurred too much code generation for little benefit. * [Struct variants](https://github.com/rust-lang/rfcs/blob/master/text/0418-struct-variants.md) are no longer feature-gated. * Trait bounds can be [polymorphic over lifetimes](https://github.com/rust-lang/rfcs/blob/master/text/0387-higher-ranked-trait-bounds.md) . Also known as ‘higher-ranked trait bounds’, this crucially allows unboxed closures to work. * Macros invocations surrounded by parens or square brackets and not terminated by a semicolon are [parsed as expressions](https://github.com/rust-lang/rfcs/blob/master/text/0378-expr-macros.md) , which makes expressions like `vec![1i32, 2, 3].len()` work as expected. * Trait objects now implement their traits automatically, and traits that can be coerced to objects now must be [object safe](https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md) . * Automatically deriving traits is now done with `#[derive(...)]` not `#[deriving(...)]` for [consistency with other naming conventions](https://github.com/rust-lang/rfcs/blob/master/text/0534-deriving2derive.md) . * Importing the containing module or enum at the same time as items or variants they contain is [now done with `self` instead of `mod`](https://github.com/rust-lang/rust/pull/22158) , as in use `foo::{self, bar}` * Glob imports are no longer feature-gated. * The `box` operator and `box` patterns have been feature-gated pending a redesign. For now unique boxes should be allocated like other containers, with `Box::new`. * Libraries * A [series](https://github.com/rust-lang/rfcs/blob/master/text/0235-collections-conventions.md) of [efforts](https://github.com/rust-lang/rfcs/blob/master/text/0509-collections-reform-part-2.md) to establish [conventions](https://github.com/rust-lang/rfcs/blob/master/text/0216-collection-views.md) for collections types has resulted in API improvements throughout the standard library. * New [APIs for error handling](https://github.com/rust-lang/rfcs/blob/master/text/0201-error-chaining.md) provide ergonomic interop between error types, and [new conventions](https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md) describe more clearly the recommended error handling strategies in Rust. * The `fail!` macro has been renamed to [`panic!`](https://github.com/rust-lang/rfcs/blob/master/text/0221-panic.md) so that it is easier to discuss failure in the context of error handling without making clarifications as to whether you are referring to the ‘fail’ macro or failure more generally. * On Linux, `OsRng` prefers the new, more reliable `getrandom` syscall when available. * The ‘serialize’ crate has been renamed ‘rustc-serialize’ and moved out of the distribution to Cargo. Although it is widely used now, it is expected to be superseded in the near future. * The `Show` formatter, typically implemented with `#[derive(Show)]` is [now requested with the `{:?}` specifier](https://github.com/rust-lang/rfcs/blob/master/text/0504-show-stabilization.md) and is intended for use by all types, for uses such as `println!` debugging. The new `String` formatter must be implemented by hand, uses the `{}` specifier, and is intended for full-fidelity conversions of things that can logically be represented as strings. * Tooling * [Flexible target specification](https://github.com/rust-lang/rfcs/blob/master/text/0131-target-specification.md) allows rustc’s code generation to be configured to support otherwise-unsupported platforms. * Rust comes with rust-gdb and rust-lldb scripts that launch their respective debuggers with Rust-appropriate pretty-printing. * The Windows installation of Rust is distributed with the MinGW components currently required to link binaries on that platform. * Misc * Nullable enum optimizations have been extended to more types so that e.g. `Option>` and `Option` take up no more space than the inner types themselves. * Work has begun on supporting AArch64. [§](https://doc.rust-lang.org/stable/releases.html#version-0120-2014-10-09) Version 0.12.0 (2014-10-09) ======================================================================================================= * ~1900 changes, numerous bugfixes * Highlights * The introductory documentation (now called The Rust Guide) has been completely rewritten, as have a number of supplementary guides. * Rust’s package manager, Cargo, continues to improve and is sometimes considered to be quite awesome. * Many API’s in `std` have been reviewed and updated for consistency with the in-development Rust coding guidelines. The standard library documentation tracks stabilization progress. * Minor libraries have been moved out-of-tree to the rust-lang org on GitHub: uuid, semver, glob, num, hexfloat, fourcc. They can be installed with Cargo. * Lifetime elision allows lifetime annotations to be left off of function declarations in many common scenarios. * Rust now works on 64-bit Windows. * Language * Indexing can be overloaded with the `Index` and `IndexMut` traits. * The `if let` construct takes a branch only if the `let` pattern matches, currently behind the ‘if\_let’ feature gate. * ‘where clauses’, a more flexible syntax for specifying trait bounds that is more aesthetic, have been added for traits and free functions. Where clauses will in the future make it possible to constrain associated types, which would be impossible with the existing syntax. * A new slicing syntax (e.g. `[0..4]`) has been introduced behind the ‘slicing\_syntax’ feature gate, and can be overloaded with the `Slice` or `SliceMut` traits. * The syntax for matching of sub-slices has been changed to use a postfix `..` instead of prefix (.e.g. `[a, b, c..]`), for consistency with other uses of `..` and to future-proof potential additional uses of the syntax. * The syntax for matching inclusive ranges in patterns has changed from `0..3` to `0...4` to be consistent with the exclusive range syntax for slicing. * Matching of sub-slices in non-tail positions (e.g. `[a.., b, c]`) has been put behind the ‘advanced\_slice\_patterns’ feature gate and may be removed in the future. * Components of tuples and tuple structs can be extracted using the `value.0` syntax, currently behind the `tuple_indexing` feature gate. * The `#[crate_id]` attribute is no longer supported; versioning is handled by the package manager. * Renaming crate imports are now written `extern crate foo as bar` instead of `extern crate bar = foo`. * Renaming use statements are now written `use foo as bar` instead of `use bar = foo`. * `let` and `match` bindings and argument names in macros are now hygienic. * The new, more efficient, closure types (‘unboxed closures’) have been added under a feature gate, ‘unboxed\_closures’. These will soon replace the existing closure types, once higher-ranked trait lifetimes are added to the language. * `move` has been added as a keyword, for indicating closures that capture by value. * Mutation and assignment is no longer allowed in pattern guards. * Generic structs and enums can now have trait bounds. * The `Share` trait is now called `Sync` to free up the term ‘shared’ to refer to ‘shared reference’ (the default reference type. * Dynamically-sized types have been mostly implemented, unifying the behavior of fat-pointer types with the rest of the type system. * As part of dynamically-sized types, the `Sized` trait has been introduced, which qualifying types implement by default, and which type parameters expect by default. To specify that a type parameter does not need to be sized, write ``. Most types are `Sized`, notable exceptions being unsized arrays (`[T]`) and trait types. * Closures can return `!`, as in `|| -> !` or `proc() -> !`. * Lifetime bounds can now be applied to type parameters and object types. * The old, reference counted GC type, `Gc` which was once denoted by the `@` sigil, has finally been removed. GC will be revisited in the future. * Libraries * Library documentation has been improved for a number of modules. * Bit-vectors, collections::bitv has been modernized. * The url crate is deprecated in favor of http://github.com/servo/rust-url, which can be installed with Cargo. * Most I/O stream types can be cloned and subsequently closed from a different thread. * A `std::time::Duration` type has been added for use in I/O methods that rely on timers, as well as in the ‘time’ crate’s `Timespec` arithmetic. * The runtime I/O abstraction layer that enabled the green thread scheduler to do non-thread-blocking I/O has been removed, along with the libuv-based implementation employed by the green thread scheduler. This will greatly simplify the future I/O work. * `collections::btree` has been rewritten to have a more idiomatic and efficient design. * Tooling * rustdoc output now indicates the stability levels of API’s. * The `--crate-name` flag can specify the name of the crate being compiled, like `#[crate_name]`. * The `-C metadata` specifies additional metadata to hash into symbol names, and `-C extra-filename` specifies additional information to put into the output filename, for use by the package manager for versioning. * debug info generation has continued to improve and should be more reliable under both gdb and lldb. * rustc has experimental support for compiling in parallel using the `-C codegen-units` flag. * rustc no longer encodes rpath information into binaries by default. * Misc * Stack usage has been optimized with LLVM lifetime annotations. * Official Rust binaries on Linux are more compatible with older kernels and distributions, built on CentOS 5.10. [§](https://doc.rust-lang.org/stable/releases.html#version-0110-2014-07-02) Version 0.11.0 (2014-07-02) ======================================================================================================= * ~1700 changes, numerous bugfixes * Language * ~\[T\] has been removed from the language. This type is superseded by the Vec type. * ~str has been removed from the language. This type is superseded by the String type. * ~T has been removed from the language. This type is superseded by the Box type. * @T has been removed from the language. This type is superseded by the standard library’s std::gc::Gc type. * Struct fields are now all private by default. * Vector indices and shift amounts are both required to be a `uint` instead of any integral type. * Byte character, byte string, and raw byte string literals are now all supported by prefixing the normal literal with a `b`. * Multiple ABIs are no longer allowed in an ABI string * The syntax for lifetimes on closures/procedures has been tweaked slightly: `<'a>|A, B|: 'b + K -> T` * Floating point modulus has been removed from the language; however it is still provided by a library implementation. * Private enum variants are now disallowed. * The `priv` keyword has been removed from the language. * A closure can no longer be invoked through a &-pointer. * The `use foo, bar, baz;` syntax has been removed from the language. * The transmute intrinsic no longer works on type parameters. * Statics now allow blocks/items in their definition. * Trait bounds are separated from objects with + instead of : now. * Objects can no longer be read while they are mutably borrowed. * The address of a static is now marked as insignificant unless the #\[inline(never)\] attribute is placed it. * The #\[unsafe\_destructor\] attribute is now behind a feature gate. * Struct literals are no longer allowed in ambiguous positions such as if, while, match, and for..in. * Declaration of lang items and intrinsics are now feature-gated by default. * Integral literals no longer default to `int`, and floating point literals no longer default to `f64`. Literals must be suffixed with an appropriate type if inference cannot determine the type of the literal. * The Box type is no longer implicitly borrowed to &mut T. * Procedures are now required to not capture borrowed references. * Libraries * The standard library is now a “facade” over a number of underlying libraries. This means that development on the standard library should be speedier due to smaller crates, as well as a clearer line between all dependencies. * A new library, libcore, lives under the standard library’s facade which is Rust’s “0-assumption” library, suitable for embedded and kernel development for example. * A regex crate has been added to the standard distribution. This crate includes statically compiled regular expressions. * The unwrap/unwrap\_err methods on Result require a Show bound for better error messages. * The return types of the std::comm primitives have been centralized around the Result type. * A number of I/O primitives have gained the ability to time out their operations. * A number of I/O primitives have gained the ability to close their reading/writing halves to cancel pending operations. * Reverse iterator methods have been removed in favor of `rev()` on their forward-iteration counterparts. * A bitflags! macro has been added to enable easy interop with C and management of bit flags. * A debug\_assert! macro is now provided which is disabled when `--cfg ndebug` is passed to the compiler. * A graphviz crate has been added for creating .dot files. * The std::cast module has been migrated into std::mem. * The std::local\_data api has been migrated from freestanding functions to being based on methods. * The Pod trait has been renamed to Copy. * jemalloc has been added as the default allocator for types. * The API for allocating memory has been changed to use proper alignment and sized deallocation * Connecting a TcpStream or binding a TcpListener is now based on a string address and a u16 port. This allows connecting to a hostname as opposed to an IP. * The Reader trait now contains a core method, read\_at\_least(), which correctly handles many repeated 0-length reads. * The process-spawning API is now centered around a builder-style Command struct. * The :? printing qualifier has been moved from the standard library to an external libdebug crate. * Eq/Ord have been renamed to PartialEq/PartialOrd. TotalEq/TotalOrd have been renamed to Eq/Ord. * The select/plural methods have been removed from format!. The escapes for { and } have also changed from { and } to {{ and }}, respectively. * The TaskBuilder API has been re-worked to be a true builder, and extension traits for spawning native/green tasks have been added. * Tooling * All breaking changes to the language or libraries now have their commit message annotated with `[breaking-change]` to allow for easy discovery of breaking changes. * The compiler will now try to suggest how to annotate lifetimes if a lifetime-related error occurs. * Debug info continues to be improved greatly with general bug fixes and better support for situations like link time optimization (LTO). * Usage of syntax extensions when cross-compiling has been fixed. * Functionality equivalent to GCC & Clang’s -ffunction-sections, -fdata-sections and –gc-sections has been enabled by default * The compiler is now stricter about where it will load module files from when a module is declared via `mod foo;`. * The #\[phase(syntax)\] attribute has been renamed to #\[phase(plugin)\]. Syntax extensions are now discovered via a “plugin registrar” type which will be extended in the future to other various plugins. * Lints have been restructured to allow for dynamically loadable lints. * A number of rustdoc improvements: * The HTML output has been visually redesigned. * Markdown is now powered by hoedown instead of sundown. * Searching heuristics have been greatly improved. * The search index has been reduced in size by a great amount. * Cross-crate documentation via `pub use` has been greatly improved. * Primitive types are now hyperlinked and documented. * Documentation has been moved from static.rust-lang.org/doc to doc.rust-lang.org * A new sandbox, play.rust-lang.org, is available for running and sharing rust code examples on-line. * Unused attributes are now more robustly warned about. * The dead\_code lint now warns about unused struct fields. * Cross-compiling to iOS is now supported. * Cross-compiling to mipsel is now supported. * Stability attributes are now inherited by default and no longer apply to intra-crate usage, only inter-crate usage. * Error message related to non-exhaustive match expressions have been greatly improved. [§](https://doc.rust-lang.org/stable/releases.html#version-010-2014-04-03) Version 0.10 (2014-04-03) ==================================================================================================== * ~1500 changes, numerous bugfixes * Language * A new RFC process is now in place for modifying the language. * Patterns with `@`\-pointers have been removed from the language. * Patterns with unique vectors (`~[T]`) have been removed from the language. * Patterns with unique strings (`~str`) have been removed from the language. * `@str` has been removed from the language. * `@[T]` has been removed from the language. * `@self` has been removed from the language. * `@Trait` has been removed from the language. * Headers on `~` allocations which contain `@` boxes inside the type for reference counting have been removed. * The semantics around the lifetimes of temporary expressions have changed, see #3511 and #11585 for more information. * Cross-crate syntax extensions are now possible, but feature gated. See #11151 for more information. This includes both `macro_rules!` macros as well as syntax extensions such as `format!`. * New lint modes have been added, and older ones have been turned on to be warn-by-default. * Unnecessary parentheses * Uppercase statics * Camel Case types * Uppercase variables * Publicly visible private types * `#[deriving]` with raw pointers * Unsafe functions can no longer be coerced to closures. * Various obscure macros such as `log_syntax!` are now behind feature gates. * The `#[simd]` attribute is now behind a feature gate. * Visibility is no longer allowed on `extern crate` statements, and unnecessary visibility (`priv`) is no longer allowed on `use` statements. * Trailing commas are now allowed in argument lists and tuple patterns. * The `do` keyword has been removed, it is now a reserved keyword. * Default type parameters have been implemented, but are feature gated. * Borrowed variables through captures in closures are now considered soundly. * `extern mod` is now `extern crate` * The `Freeze` trait has been removed. * The `Share` trait has been added for types that can be shared among threads. * Labels in macros are now hygienic. * Expression/statement macro invocations can be delimited with `{}` now. * Treatment of types allowed in `static mut` locations has been tweaked. * The `*` and `.` operators are now overloadable through the `Deref` and `DerefMut` traits. * `~Trait` and `proc` no longer have `Send` bounds by default. * Partial type hints are now supported with the `_` type marker. * An `Unsafe` type was introduced for interior mutability. It is now considered undefined to transmute from `&T` to `&mut T` without using the `Unsafe` type. * The #\[linkage\] attribute was implemented for extern statics/functions. * The inner attribute syntax has changed from `#[foo];` to `#![foo]`. * `Pod` was renamed to `Copy`. * Libraries * The `libextra` library has been removed. It has now been decomposed into component libraries with smaller and more focused nuggets of functionality. The full list of libraries can be found on the documentation index page. * std: `std::condition` has been removed. All I/O errors are now propagated through the `Result` type. In order to assist with error handling, a `try!` macro for unwrapping errors with an early return and a lint for unused results has been added. See #12039 for more information. * std: The `vec` module has been renamed to `slice`. * std: A new vector type, `Vec`, has been added in preparation for DST. This will become the only growable vector in the future. * std: `std::io` now has more public re-exports. Types such as `BufferedReader` are now found at `std::io::BufferedReader` instead of `std::io::buffered::BufferedReader`. * std: `print` and `println` are no longer in the prelude, the `print!` and `println!` macros are intended to be used instead. * std: `Rc` now has a `Weak` pointer for breaking cycles, and it no longer attempts to statically prevent cycles. * std: The standard distribution is adopting the policy of pushing failure to the user rather than failing in libraries. Many functions (such as `slice::last()`) now return `Option` instead of `T` + failing. * std: `fmt::Default` has been renamed to `fmt::Show`, and it now has a new deriving mode: `#[deriving(Show)]`. * std: `ToStr` is now implemented for all types implementing `Show`. * std: The formatting trait methods now take `&self` instead of `&T` * std: The `invert()` method on iterators has been renamed to `rev()` * std: `std::num` has seen a reduction in the genericity of its traits, consolidating functionality into a few core traits. * std: Backtraces are now printed on task failure if the environment variable `RUST_BACKTRACE` is present. * std: Naming conventions for iterators have been standardized. More details can be found on the wiki’s style guide. * std: `eof()` has been removed from the `Reader` trait. Specific types may still implement the function. * std: Networking types are now cloneable to allow simultaneous reads/writes. * std: `assert_approx_eq!` has been removed * std: The `e` and `E` formatting specifiers for floats have been added to print them in exponential notation. * std: The `Times` trait has been removed * std: Indications of variance and opting out of builtin bounds is done through marker types in `std::kinds::marker` now * std: `hash` has been rewritten, `IterBytes` has been removed, and `#[deriving(Hash)]` is now possible. * std: `SharedChan` has been removed, `Sender` is now cloneable. * std: `Chan` and `Port` were renamed to `Sender` and `Receiver`. * std: `Chan::new` is now `channel()`. * std: A new synchronous channel type has been implemented. * std: A `select!` macro is now provided for selecting over `Receiver`s. * std: `hashmap` and `trie` have been moved to `libcollections` * std: `run` has been rolled into `io::process` * std: `assert_eq!` now uses `{}` instead of `{:?}` * std: The equality and comparison traits have seen some reorganization. * std: `rand` has moved to `librand`. * std: `to_{lower,upper}case` has been implemented for `char`. * std: Logging has been moved to `liblog`. * collections: `HashMap` has been rewritten for higher performance and less memory usage. * native: The default runtime is now `libnative`. If `libgreen` is desired, it can be booted manually. The runtime guide has more information and examples. * native: All I/O functionality except signals has been implemented. * green: Task spawning with `libgreen` has been optimized with stack caching and various trimming of code. * green: Tasks spawned by `libgreen` now have an unmapped guard page. * sync: The `extra::sync` module has been updated to modern rust (and moved to the `sync` library), tweaking and improving various interfaces while dropping redundant functionality. * sync: A new `Barrier` type has been added to the `sync` library. * sync: An efficient mutex for native and green tasks has been implemented. * serialize: The `base64` module has seen some improvement. It treats newlines better, has non-string error values, and has seen general cleanup. * fourcc: A `fourcc!` macro was introduced * hexfloat: A `hexfloat!` macro was implemented for specifying floats via a hexadecimal literal. * Tooling * `rustpkg` has been deprecated and removed from the main repository. Its replacement, `cargo`, is under development. * Nightly builds of rust are now available * The memory usage of rustc has been improved many times throughout this release cycle. * The build process supports disabling rpath support for the rustc binary itself. * Code generation has improved in some cases, giving more information to the LLVM optimization passes to enable more extensive optimizations. * Debuginfo compatibility with lldb on OSX has been restored. * The master branch is now gated on an android bot, making building for android much more reliable. * Output flags have been centralized into one `--emit` flag. * Crate type flags have been centralized into one `--crate-type` flag. * Codegen flags have been consolidated behind a `-C` flag. * Linking against outdated crates now has improved error messages. * Error messages with lifetimes will often suggest how to annotate the function to fix the error. * Many more types are documented in the standard library, and new guides were written. * Many `rustdoc` improvements: * code blocks are syntax highlighted. * render standalone markdown files. * the –test flag tests all code blocks by default. * exported macros are displayed. * re-exported types have their documentation inlined at the location of the first re-export. * search works across crates that have been rendered to the same output directory. [§](https://doc.rust-lang.org/stable/releases.html#version-09-2014-01-09) Version 0.9 (2014-01-09) ================================================================================================== * ~1800 changes, numerous bugfixes * Language * The `float` type has been removed. Use `f32` or `f64` instead. * A new facility for enabling experimental features (feature gating) has been added, using the crate-level `#[feature(foo)]` attribute. * Managed boxes (@) are now behind a feature gate (`#[feature(managed_boxes)]`) in preparation for future removal. Use the standard library’s `Gc` or `Rc` types instead. * `@mut` has been removed. Use `std::cell::{Cell, RefCell}` instead. * Jumping back to the top of a loop is now done with `continue` instead of `loop`. * Strings can no longer be mutated through index assignment. * Raw strings can be created via the basic `r"foo"` syntax or with matched hash delimiters, as in `r###"foo"###`. * `~fn` is now written `proc (args) -> retval { ... }` and may only be called once. * The `&fn` type is now written `|args| -> ret` to match the literal form. * `@fn`s have been removed. * `do` only works with procs in order to make it obvious what the cost of `do` is. * Single-element tuple-like structs can no longer be dereferenced to obtain the inner value. A more comprehensive solution for overloading the dereference operator will be provided in the future. * The `#[link(...)]` attribute has been replaced with `#[crate_id = "name#vers"]`. * Empty `impl`s must be terminated with empty braces and may not be terminated with a semicolon. * Keywords are no longer allowed as lifetime names; the `self` lifetime no longer has any special meaning. * The old `fmt!` string formatting macro has been removed. * `printf!` and `printfln!` (old-style formatting) removed in favor of `print!` and `println!`. * `mut` works in patterns now, as in `let (mut x, y) = (1, 2);`. * The `extern mod foo (name = "bar")` syntax has been removed. Use `extern mod foo = "bar"` instead. * New reserved keywords: `alignof`, `offsetof`, `sizeof`. * Macros can have attributes. * Macros can expand to items with attributes. * Macros can expand to multiple items. * The `asm!` macro is feature-gated (`#[feature(asm)]`). * Comments may be nested. * Values automatically coerce to trait objects they implement, without an explicit `as`. * Enum discriminants are no longer an entire word but as small as needed to contain all the variants. The `repr` attribute can be used to override the discriminant size, as in `#[repr(int)]` for integer-sized, and `#[repr(C)]` to match C enums. * Non-string literals are not allowed in attributes (they never worked). * The FFI now supports variadic functions. * Octal numeric literals, as in `0o7777`. * The `concat!` syntax extension performs compile-time string concatenation. * The `#[fixed_stack_segment]` and `#[rust_stack]` attributes have been removed as Rust no longer uses segmented stacks. * Non-ascii identifiers are feature-gated (`#[feature(non_ascii_idents)]`). * Ignoring all fields of an enum variant or tuple-struct is done with `..`, not `*`; ignoring remaining fields of a struct is also done with `..`, not `_`; ignoring a slice of a vector is done with `..`, not `.._`. * `rustc` supports the “win64” calling convention via `extern "win64"`. * `rustc` supports the “system” calling convention, which defaults to the preferred convention for the target platform, “stdcall” on 32-bit Windows, “C” elsewhere. * The `type_overflow` lint (default: warn) checks literals for overflow. * The `unsafe_block` lint (default: allow) checks for usage of `unsafe`. * The `attribute_usage` lint (default: warn) warns about unknown attributes. * The `unknown_features` lint (default: warn) warns about unknown feature gates. * The `dead_code` lint (default: warn) checks for dead code. * Rust libraries can be linked statically to one another * `#[link_args]` is behind the `link_args` feature gate. * Native libraries are now linked with `#[link(name = "foo")]` * Native libraries can be statically linked to a rust crate (`#[link(name = "foo", kind = "static")]`). * Native OS X frameworks are now officially supported (`#[link(name = "foo", kind = "framework")]`). * The `#[thread_local]` attribute creates thread-local (not task-local) variables. Currently behind the `thread_local` feature gate. * The `return` keyword may be used in closures. * Types that can be copied via a memcpy implement the `Pod` kind. * The `cfg` attribute can now be used on struct fields and enum variants. * Libraries * std: The `option` and `result` API’s have been overhauled to make them simpler, more consistent, and more composable. * std: The entire `std::io` module has been replaced with one that is more comprehensive and that properly interfaces with the underlying scheduler. File, TCP, UDP, Unix sockets, pipes, and timers are all implemented. * std: `io::util` contains a number of useful implementations of `Reader` and `Writer`, including `NullReader`, `NullWriter`, `ZeroReader`, `TeeReader`. * std: The reference counted pointer type `extra::rc` moved into std. * std: The `Gc` type in the `gc` module will replace `@` (it is currently just a wrapper around it). * std: The `Either` type has been removed. * std: `fmt::Default` can be implemented for any type to provide default formatting to the `format!` macro, as in `format!("{}", myfoo)`. * std: The `rand` API continues to be tweaked. * std: The `rust_begin_unwind` function, useful for inserting breakpoints on failure in gdb, is now named `rust_fail`. * std: The `each_key` and `each_value` methods on `HashMap` have been replaced by the `keys` and `values` iterators. * std: Functions dealing with type size and alignment have moved from the `sys` module to the `mem` module. * std: The `path` module was written and API changed. * std: `str::from_utf8` has been changed to cast instead of allocate. * std: `starts_with` and `ends_with` methods added to vectors via the `ImmutableEqVector` trait, which is in the prelude. * std: Vectors can be indexed with the `get_opt` method, which returns `None` if the index is out of bounds. * std: Task failure no longer propagates between tasks, as the model was complex, expensive, and incompatible with thread-based tasks. * std: The `Any` type can be used for dynamic typing. * std: `~Any` can be passed to the `fail!` macro and retrieved via `task::try`. * std: Methods that produce iterators generally do not have an `_iter` suffix now. * std: `cell::Cell` and `cell::RefCell` can be used to introduce mutability roots (mutable fields, etc.). Use instead of e.g. `@mut`. * std: `util::ignore` renamed to `prelude::drop`. * std: Slices have `sort` and `sort_by` methods via the `MutableVector` trait. * std: `vec::raw` has seen a lot of cleanup and API changes. * std: The standard library no longer includes any C++ code, and very minimal C, eliminating the dependency on libstdc++. * std: Runtime scheduling and I/O functionality has been factored out into extensible interfaces and is now implemented by two different crates: libnative, for native threading and I/O; and libgreen, for green threading and I/O. This paves the way for using the standard library in more limited embedded environments. * std: The `comm` module has been rewritten to be much faster, have a simpler, more consistent API, and to work for both native and green threading. * std: All libuv dependencies have been moved into the rustuv crate. * native: New implementations of runtime scheduling on top of OS threads. * native: New native implementations of TCP, UDP, file I/O, process spawning, and other I/O. * green: The green thread scheduler and message passing types are almost entirely lock-free. * extra: The `flatpipes` module had bitrotted and was removed. * extra: All crypto functions have been removed and Rust now has a policy of not reimplementing crypto in the standard library. In the future crypto will be provided by external crates with bindings to established libraries. * extra: `c_vec` has been modernized. * extra: The `sort` module has been removed. Use the `sort` method on mutable slices. * Tooling * The `rust` and `rusti` commands have been removed, due to lack of maintenance. * `rustdoc` was completely rewritten. * `rustdoc` can test code examples in documentation. * `rustpkg` can test packages with the argument, ‘test’. * `rustpkg` supports arbitrary dependencies, including C libraries. * `rustc`’s support for generating debug info is improved again. * `rustc` has better error reporting for unbalanced delimiters. * `rustc`’s JIT support was removed due to bitrot. * Executables and static libraries can be built with LTO (-Z lto) * `rustc` adds a `--dep-info` flag for communicating dependencies to build tools. [§](https://doc.rust-lang.org/stable/releases.html#version-08-2013-09-26) Version 0.8 (2013-09-26) ================================================================================================== * ~2200 changes, numerous bugfixes * Language * The `for` loop syntax has changed to work with the `Iterator` trait. * At long last, unwinding works on Windows. * Default methods are ready for use. * Many trait inheritance bugs fixed. * Owned and borrowed trait objects work more reliably. * `copy` is no longer a keyword. It has been replaced by the `Clone` trait. * rustc can omit emission of code for the `debug!` macro if it is passed `--cfg ndebug` * mod.rs is now “blessed”. When loading `mod foo;`, rustc will now look for foo.rs, then foo/mod.rs, and will generate an error when both are present. * Strings no longer contain trailing nulls. The new `std::c_str` module provides new mechanisms for converting to C strings. * The type of foreign functions is now `extern "C" fn` instead of \`\*u8’. * The FFI has been overhauled such that foreign functions are called directly, instead of through a stack-switching wrapper. * Calling a foreign function must be done through a Rust function with the `#[fixed_stack_segment]` attribute. * The `externfn!` macro can be used to declare both a foreign function and a `#[fixed_stack_segment]` wrapper at once. * `pub` and `priv` modifiers on `extern` blocks are no longer parsed. * `unsafe` is no longer allowed on extern fns - they are all unsafe. * `priv` is disallowed everywhere except for struct fields and enum variants. * `&T` (besides `&'static T`) is no longer allowed in `@T`. * `ref` bindings in irrefutable patterns work correctly now. * `char` is now prevented from containing invalid code points. * Casting to `bool` is no longer allowed. * `\0` is now accepted as an escape in chars and strings. * `yield` is a reserved keyword. * `typeof` is a reserved keyword. * Crates may be imported by URL with `extern mod foo = "url";`. * Explicit enum discriminants may be given as uints as in `enum E { V = 0u }` * Static vectors can be initialized with repeating elements, e.g. `static foo: [u8, .. 100]: [0, .. 100];`. * Static structs can be initialized with functional record update, e.g. `static foo: Foo = Foo { a: 5, .. bar };`. * `cfg!` can be used to conditionally execute code based on the crate configuration, similarly to `#[cfg(...)]`. * The `unnecessary_qualification` lint detects unneeded module prefixes (default: allow). * Arithmetic operations have been implemented on the SIMD types in `std::unstable::simd`. * Exchange allocation headers were removed, reducing memory usage. * `format!` implements a completely new, extensible, and higher-performance string formatting system. It will replace `fmt!`. * `print!` and `println!` write formatted strings (using the `format!` extension) to stdout. * `write!` and `writeln!` write formatted strings (using the `format!` extension) to the new Writers in `std::rt::io`. * The library section in which a function or static is placed may be specified with `#[link_section = "..."]`. * The `proto!` syntax extension for defining bounded message protocols was removed. * `macro_rules!` is hygienic for `let` declarations. * The `#[export_name]` attribute specifies the name of a symbol. * `unreachable!` can be used to indicate unreachable code, and fails if executed. * Libraries * std: Transitioned to the new runtime, written in Rust. * std: Added an experimental I/O library, `rt::io`, based on the new runtime. * std: A new generic `range` function was added to the prelude, replacing `uint::range` and friends. * std: `range_rev` no longer exists. Since range is an iterator it can be reversed with `range(lo, hi).invert()`. * std: The `chain` method on option renamed to `and_then`; `unwrap_or_default` renamed to `unwrap_or`. * std: The `iterator` module was renamed to `iter`. * std: Integral types now support the `checked_add`, `checked_sub`, and `checked_mul` operations for detecting overflow. * std: Many methods in `str`, `vec`, `option,` result\` were renamed for consistency. * std: Methods are standardizing on conventions for casting methods: `to_foo` for copying, `into_foo` for moving, `as_foo` for temporary and cheap casts. * std: The `CString` type in `c_str` provides new ways to convert to and from C strings. * std: `DoubleEndedIterator` can yield elements in two directions. * std: The `mut_split` method on vectors partitions an `&mut [T]` into two splices. * std: `str::from_bytes` renamed to `str::from_utf8`. * std: `pop_opt` and `shift_opt` methods added to vectors. * std: The task-local data interface no longer uses @, and keys are no longer function pointers. * std: The `swap_unwrap` method of `Option` renamed to `take_unwrap`. * std: Added `SharedPort` to `comm`. * std: `Eq` has a default method for `ne`; only `eq` is required in implementations. * std: `Ord` has default methods for `le`, `gt` and `ge`; only `lt` is required in implementations. * std: `is_utf8` performance is improved, impacting many string functions. * std: `os::MemoryMap` provides cross-platform mmap. * std: `ptr::offset` is now unsafe, but also more optimized. Offsets that are not ‘in-bounds’ are considered undefined. * std: Many freestanding functions in `vec` removed in favor of methods. * std: Many freestanding functions on scalar types removed in favor of methods. * std: Many options to task builders were removed since they don’t make sense in the new scheduler design. * std: More containers implement `FromIterator` so can be created by the `collect` method. * std: More complete atomic types in `unstable::atomics`. * std: `comm::PortSet` removed. * std: Mutating methods in the `Set` and `Map` traits have been moved into the `MutableSet` and `MutableMap` traits. `Container::is_empty`, `Map::contains_key`, `MutableMap::insert`, and `MutableMap::remove` have default implementations. * std: Various `from_str` functions were removed in favor of a generic `from_str` which is available in the prelude. * std: `util::unreachable` removed in favor of the `unreachable!` macro. * extra: `dlist`, the doubly-linked list was modernized. * extra: Added a `hex` module with `ToHex` and `FromHex` traits. * extra: Added `glob` module, replacing `std::os::glob`. * extra: `rope` was removed. * extra: `deque` was renamed to `ringbuf`. `RingBuf` implements `Deque`. * extra: `net`, and `timer` were removed. The experimental replacements are `std::rt::io::net` and `std::rt::io::timer`. * extra: Iterators implemented for `SmallIntMap`. * extra: Iterators implemented for `Bitv` and `BitvSet`. * extra: `SmallIntSet` removed. Use `BitvSet`. * extra: Performance of JSON parsing greatly improved. * extra: `semver` updated to SemVer 2.0.0. * extra: `term` handles more terminals correctly. * extra: `dbg` module removed. * extra: `par` module removed. * extra: `future` was cleaned up, with some method renames. * extra: Most free functions in `getopts` were converted to methods. * Other * rustc’s debug info generation (`-Z debug-info`) is greatly improved. * rustc accepts `--target-cpu` to compile to a specific CPU architecture, similarly to gcc’s `--march` flag. * rustc’s performance compiling small crates is much better. * rustpkg has received many improvements. * rustpkg supports git tags as package IDs. * rustpkg builds into target-specific directories so it can be used for cross-compiling. * The number of concurrent test tasks is controlled by the environment variable RUST\_TEST\_TASKS. * The test harness can now report metrics for benchmarks. * All tools have man pages. * Programs compiled with `--test` now support the `-h` and `--help` flags. * The runtime uses jemalloc for allocations. * Segmented stacks are temporarily disabled as part of the transition to the new runtime. Stack overflows are possible! * A new documentation backend, rustdoc\_ng, is available for use. It is still invoked through the normal `rustdoc` command. [§](https://doc.rust-lang.org/stable/releases.html#version-07-2013-07-03) Version 0.7 (2013-07-03) ================================================================================================== * ~2000 changes, numerous bugfixes * Language * `impl`s no longer accept a visibility qualifier. Put them on methods instead. * The borrow checker has been rewritten with flow-sensitivity, fixing many bugs and inconveniences. * The `self` parameter no longer implicitly means `&'self self`, and can be explicitly marked with a lifetime. * Overloadable compound operators (`+=`, etc.) have been temporarily removed due to bugs. * The `for` loop protocol now requires `for`\-iterators to return `bool` so they compose better. * The `Durable` trait is replaced with the `'static` bounds. * Trait default methods work more often. * Structs with the `#[packed]` attribute have byte alignment and no padding between fields. * Type parameters bound by `Copy` must now be copied explicitly with the `copy` keyword. * It is now illegal to move out of a dereferenced unsafe pointer. * `Option<~T>` is now represented as a nullable pointer. * `@mut` does dynamic borrow checks correctly. * The `main` function is only detected at the topmost level of the crate. The `#[main]` attribute is still valid anywhere. * Struct fields may no longer be mutable. Use inherited mutability. * The `#[no_send]` attribute makes a type that would otherwise be `Send`, not. * The `#[no_freeze]` attribute makes a type that would otherwise be `Freeze`, not. * Unbounded recursion will abort the process after reaching the limit specified by the `RUST_MAX_STACK` environment variable (default: 1GB). * The `vecs_implicitly_copyable` lint mode has been removed. Vectors are never implicitly copyable. * `#[static_assert]` makes compile-time assertions about static bools. * At long last, ‘argument modes’ no longer exist. * The rarely used `use mod` statement no longer exists. * Syntax extensions * `fail!` and `assert!` accept `~str`, `&'static str` or `fmt!`\-style argument list. * `Encodable`, `Decodable`, `Ord`, `TotalOrd`, `TotalEq`, `DeepClone`, `Rand`, `Zero` and `ToStr` can all be automatically derived with `#[deriving(...)]`. * The `bytes!` macro returns a vector of bytes for string, u8, char, and unsuffixed integer literals. * Libraries * The `core` crate was renamed to `std`. * The `std` crate was renamed to `extra`. * More and improved documentation. * std: `iterator` module for external iterator objects. * Many old-style (internal, higher-order function) iterators replaced by implementations of `Iterator`. * std: Many old internal vector and string iterators, incl. `any`, `all`. removed. * std: The `finalize` method of `Drop` renamed to `drop`. * std: The `drop` method now takes `&mut self` instead of `&self`. * std: The prelude no longer re-exports any modules, only types and traits. * std: Prelude additions: `print`, `println`, `FromStr`, `ApproxEq`, `Equiv`, `Iterator`, `IteratorUtil`, many numeric traits, many tuple traits. * std: New numeric traits: `Fractional`, `Real`, `RealExt`, `Integer`, `Ratio`, `Algebraic`, `Trigonometric`, `Exponential`, `Primitive`. * std: Tuple traits and accessors defined for up to 12-tuples, e.g. `(0, 1, 2).n2()` or `(0, 1, 2).n2_ref()`. * std: Many types implement `Clone`. * std: `path` type renamed to `Path`. * std: `mut` module and `Mut` type removed. * std: Many standalone functions removed in favor of methods and iterators in `vec`, `str`. In the future methods will also work as functions. * std: `reinterpret_cast` removed. Use `transmute`. * std: ascii string handling in `std::ascii`. * std: `Rand` is implemented for ~/@. * std: `run` module for spawning processes overhauled. * std: Various atomic types added to `unstable::atomic`. * std: Various types implement `Zero`. * std: `LinearMap` and `LinearSet` renamed to `HashMap` and `HashSet`. * std: Borrowed pointer functions moved from `ptr` to `borrow`. * std: Added `os::mkdir_recursive`. * std: Added `os::glob` function performs filesystems globs. * std: `FuzzyEq` renamed to `ApproxEq`. * std: `Map` now defines `pop` and `swap` methods. * std: `Cell` constructors converted to static methods. * extra: `rc` module adds the reference counted pointers, `Rc` and `RcMut`. * extra: `flate` module moved from `std` to `extra`. * extra: `fileinput` module for iterating over a series of files. * extra: `Complex` number type and `complex` module. * extra: `Rational` number type and `rational` module. * extra: `BigInt`, `BigUint` implement numeric and comparison traits. * extra: `term` uses terminfo now, is more correct. * extra: `arc` functions converted to methods. * extra: Implementation of fixed output size variations of SHA-2. * Tooling * `unused_variables` lint mode for unused variables (default: warn). * `unused_unsafe` lint mode for detecting unnecessary `unsafe` blocks (default: warn). * `unused_mut` lint mode for identifying unused `mut` qualifiers (default: warn). * `dead_assignment` lint mode for unread variables (default: warn). * `unnecessary_allocation` lint mode detects some heap allocations that are immediately borrowed so could be written without allocating (default: warn). * `missing_doc` lint mode (default: allow). * `unreachable_code` lint mode (default: warn). * The `rusti` command has been rewritten and a number of bugs addressed. * rustc outputs in color on more terminals. * rustc accepts a `--link-args` flag to pass arguments to the linker. * rustc accepts a `-Z print-link-args` flag for debugging linkage. * Compiling with `-g` will make the binary record information about dynamic borrowcheck failures for debugging. * rustdoc has a nicer stylesheet. * Various improvements to rustdoc. * Improvements to rustpkg (see the detailed release notes). [§](https://doc.rust-lang.org/stable/releases.html#version-06-2013-04-03) Version 0.6 (2013-04-03) ================================================================================================== * ~2100 changes, numerous bugfixes * Syntax changes * The self type parameter in traits is now spelled `Self` * The `self` parameter in trait and impl methods must now be explicitly named (for example: `fn f(&self) { }`). Implicit self is deprecated. * Static methods no longer require the `static` keyword and instead are distinguished by the lack of a `self` parameter * Replaced the `Durable` trait with the `'static` lifetime * The old closure type syntax with the trailing sigil has been removed in favor of the more consistent leading sigil * `super` is a keyword, and may be prefixed to paths * Trait bounds are separated with `+` instead of whitespace * Traits are implemented with `impl Trait for Type` instead of `impl Type: Trait` * Lifetime syntax is now `&'l foo` instead of `&l/foo` * The `export` keyword has finally been removed * The `move` keyword has been removed (see “Semantic changes”) * The interior mutability qualifier on vectors, `[mut T]`, has been removed. Use `&mut [T]`, etc. * `mut` is no longer valid in `~mut T`. Use inherited mutability * `fail` is no longer a keyword. Use `fail!()` * `assert` is no longer a keyword. Use `assert!()` * `log` is no longer a keyword. use `debug!`, etc. * 1-tuples may be represented as `(T,)` * Struct fields may no longer be `mut`. Use inherited mutability, `@mut T`, `core::mut` or `core::cell` * `extern mod { ... }` is no longer valid syntax for foreign function modules. Use extern blocks: `extern { ... }` * Newtype enums removed. Use tuple-structs. * Trait implementations no longer support visibility modifiers * Pattern matching over vectors improved and expanded * `const` renamed to `static` to correspond to lifetime name, and make room for future `static mut` unsafe mutable globals. * Replaced `#[deriving_eq]` with `#[deriving(Eq)]`, etc. * `Clone` implementations can be automatically generated with `#[deriving(Clone)]` * Casts to traits must use a pointer sigil, e.g. `@foo as @Bar` instead of `foo as Bar`. * Fixed length vector types are now written as `[int, .. 3]` instead of `[int * 3]`. * Fixed length vector types can express the length as a constant expression. (ex: `[int, .. GL_BUFFER_SIZE - 2]`) * Semantic changes * Types with owned pointers or custom destructors move by default, eliminating the `move` keyword * All foreign functions are considered unsafe * &mut is now unaliasable * Writes to borrowed @mut pointers are prevented dynamically * () has size 0 * The name of the main function can be customized using #\[main\] * The default type of an inferred closure is &fn instead of @fn * `use` statements may no longer be “chained” - they cannot import identifiers imported by previous `use` statements * `use` statements are crate relative, importing from the “top” of the crate by default. Paths may be prefixed with `super::` or `self::` to change the search behavior. * Method visibility is inherited from the implementation declaration * Structural records have been removed * Many more types can be used in static items, including enums ’static-lifetime pointers and vectors * Pattern matching over vectors improved and expanded * Typechecking of closure types has been overhauled to improve inference and eliminate unsoundness * Macros leave scope at the end of modules, unless that module is tagged with #\[macro\_escape\] * Libraries * Added big integers to `std::bigint` * Removed `core::oldcomm` module * Added pipe-based `core::comm` module * Numeric traits have been reorganized under `core::num` * `vec::slice` finally returns a slice * `debug!` and friends don’t require a format string, e.g. `debug!(Foo)` * Containers reorganized around traits in `core::container` * `core::dvec` removed, `~[T]` is a drop-in replacement * `core::send_map` renamed to `core::hashmap` * `std::map` removed; replaced with `core::hashmap` * `std::treemap` reimplemented as an owned balanced tree * `std::deque` and `std::smallintmap` reimplemented as owned containers * `core::trie` added as a fast ordered map for integer keys * Set types added to `core::hashmap`, `core::trie` and `std::treemap` * `Ord` split into `Ord` and `TotalOrd`. `Ord` is still used to overload the comparison operators, whereas `TotalOrd` is used by certain container types * Other * Replaced the ‘cargo’ package manager with ‘rustpkg’ * Added all-purpose ‘rust’ tool * `rustc --test` now supports benchmarks with the `#[bench]` attribute * rustc now _attempts_ to offer spelling suggestions * Improved support for ARM and Android * Preliminary MIPS backend * Improved foreign function ABI implementation for x86, x86\_64 * Various memory usage improvements * Rust code may be embedded in foreign code under limited circumstances * Inline assembler supported by new asm!() syntax extension. [§](https://doc.rust-lang.org/stable/releases.html#version-05-2012-12-21) Version 0.5 (2012-12-21) ================================================================================================== * ~900 changes, numerous bugfixes * Syntax changes * Removed `<-` move operator * Completed the transition from the `#fmt` extension syntax to `fmt!` * Removed old fixed length vector syntax - `[T]/N` * New token-based quasi-quoters, `quote_tokens!`, `quote_expr!`, etc. * Macros may now expand to items and statements * `a.b()` is always parsed as a method call, never as a field projection * `Eq` and `IterBytes` implementations can be automatically generated with `#[deriving_eq]` and `#[deriving_iter_bytes]` respectively * Removed the special crate language for `.rc` files * Function arguments may consist of any irrefutable pattern * Semantic changes * `&` and `~` pointers may point to objects * Tuple structs - `struct Foo(Bar, Baz)`. Will replace newtype enums. * Enum variants may be structs * Destructors can be added to all nominal types with the Drop trait * Structs and nullary enum variants may be constants * Values that cannot be implicitly copied are now automatically moved without writing `move` explicitly * `&T` may now be coerced to `*T` * Coercions happen in `let` statements as well as function calls * `use` statements now take crate-relative paths * The module and type namespaces have been merged so that static method names can be resolved under the trait in which they are declared * Improved support for language features * Trait inheritance works in many scenarios * More support for explicit self arguments in methods - `self`, `&self` `@self`, and `~self` all generally work as expected * Static methods work in more situations * Experimental: Traits may declare default methods for the implementations to use * Libraries * New condition handling system in `core::condition` * Timsort added to `std::sort` * New priority queue, `std::priority_queue` * Pipes for serializable types, \`std::flatpipes’ * Serialization overhauled to be trait-based * Expanded `getopts` definitions * Moved futures to `std` * More functions are pure now * `core::comm` renamed to `oldcomm`. Still deprecated * `rustdoc` and `cargo` are libraries now * Misc * Added a preliminary REPL, `rusti` * License changed from MIT to dual MIT/APL2 [§](https://doc.rust-lang.org/stable/releases.html#version-04-2012-10-15) Version 0.4 (2012-10-15) ================================================================================================== * ~2000 changes, numerous bugfixes * Syntax * All keywords are now strict and may not be used as identifiers anywhere * Keyword removal: ‘again’, ‘import’, ‘check’, ‘new’, ‘owned’, ‘send’, ‘of’, ‘with’, ‘to’, ‘class’. * Classes are replaced with simpler structs * Explicit method self types * `ret` became `return` and `alt` became `match` * `import` is now `use`; `use is now` extern mod\` * `extern mod { ... }` is now `extern { ... }` * `use mod` is the recommended way to import modules * `pub` and `priv` replace deprecated export lists * The syntax of `match` pattern arms now uses fat arrow (=>) * `main` no longer accepts an args vector; use `os::args` instead * Semantics * Trait implementations are now coherent, ala Haskell typeclasses * Trait methods may be static * Argument modes are deprecated * Borrowed pointers are much more mature and recommended for use * Strings and vectors in the static region are stored in constant memory * Typestate was removed * Resolution rewritten to be more reliable * Support for ‘dual-mode’ data structures (freezing and thawing) * Libraries * Most binary operators can now be overloaded via the traits in \`core::ops’ * `std::net::url` for representing URLs * Sendable hash maps in `core::send_map` * \`core::task’ gained a (currently unsafe) task-local storage API * Concurrency * An efficient new intertask communication primitive called the pipe, along with a number of higher-level channel types, in `core::pipes` * `std::arc`, an atomically reference counted, immutable, shared memory type * `std::sync`, various exotic synchronization tools based on arcs and pipes * Futures are now based on pipes and sendable * More robust linked task failure * Improved task builder API * Other * Improved error reporting * Preliminary JIT support * Preliminary work on precise GC * Extensive architectural improvements to rustc * Begun a transition away from buggy C++-based reflection (shape) code to Rust-based (visitor) code * All hash functions and tables converted to secure, randomized SipHash [§](https://doc.rust-lang.org/stable/releases.html#version-03--2012-07-12) Version 0.3 (2012-07-12) =================================================================================================== * ~1900 changes, numerous bugfixes * New coding conveniences * Integer-literal suffix inference * Per-item control over warnings, errors * #\[cfg(windows)\] and #\[cfg(unix)\] attributes * Documentation comments * More compact closure syntax * ‘do’ expressions for treating higher-order functions as control structures * \*-patterns (wildcard extended to all constructor fields) * Semantic cleanup * Name resolution pass and exhaustiveness checker rewritten * Region pointers and borrow checking supersede alias analysis * Init-ness checking is now provided by a region-based liveness pass instead of the typestate pass; same for last-use analysis * Extensive work on region pointers * Experimental new language features * Slices and fixed-size, interior-allocated vectors * #!-comments for lang versioning, shell execution * Destructors and iface implementation for classes; type-parameterized classes and class methods * ‘const’ type kind for types that can be used to implement shared-memory concurrency patterns * Type reflection * Removal of various obsolete features * Keywords: ‘be’, ‘prove’, ‘syntax’, ‘note’, ‘mutable’, ‘bind’, ‘crust’, ‘native’ (now ‘extern’), ‘cont’ (now ‘again’) * Constructs: do-while loops (‘do’ repurposed), fn binding, resources (replaced by destructors) * Compiler reorganization * Syntax-layer of compiler split into separate crate * Clang (from LLVM project) integrated into build * Typechecker split into sub-modules * New library code * New time functions * Extension methods for many built-in types * Arc: atomic-refcount read-only / exclusive-use shared cells * Par: parallel map and search routines * Extensive work on libuv interface * Much vector code moved to libraries * Syntax extensions: #line, #col, #file, #mod, #stringify, #include, #include\_str, #include\_bin * Tool improvements * Cargo automatically resolves dependencies [§](https://doc.rust-lang.org/stable/releases.html#version-02--2012-03-29) Version 0.2 (2012-03-29) =================================================================================================== * > 1500 changes, numerous bugfixes * New docs and doc tooling * New port: FreeBSD x86\_64 * Compilation model enhancements * Generics now specialized, multiply instantiated * Functions now inlined across separate crates * Scheduling, stack and threading fixes * Noticeably improved message-passing performance * Explicit schedulers * Callbacks from C * Helgrind clean * Experimental new language features * Operator overloading * Region pointers * Classes * Various language extensions * C-callback function types: ‘crust fn …’ * Infinite-loop construct: ‘loop { … }’ * Shorten ‘mutable’ to ‘mut’ * Required mutable-local qualifier: ‘let mut …’ * Basic glob-exporting: ‘export foo::\*;’ * Alt now exhaustive, ‘alt check’ for runtime-checked * Block-function form of ‘for’ loop, with ‘break’ and ‘ret’. * New library code * AST quasi-quote syntax extension * Revived libuv interface * New modules: core::{future, iter}, std::arena * Merged per-platform std::{os\*, fs\*} to core::{libc, os} * Extensive cleanup, regularization in libstd, libcore [§](https://doc.rust-lang.org/stable/releases.html#version-01--2012-01-20) Version 0.1 (2012-01-20) =================================================================================================== * Most language features work, including: * Unique pointers, unique closures, move semantics * Interface-constrained generics * Static interface dispatch * Stack growth * Multithread task scheduling * Typestate predicates * Failure unwinding, destructors * Pattern matching and destructuring assignment * Lightweight block-lambda syntax * Preliminary macro-by-example * Compiler works with the following configurations: * Linux: x86 and x86\_64 hosts and targets * macOS: x86 and x86\_64 hosts and targets * Windows: x86 hosts and targets * Cross compilation / multi-target configuration supported. * Preliminary API-documentation and package-management tools included. Known issues: * Documentation is incomplete. * Performance is below intended target. * Standard library APIs are subject to extensive change, reorganization. * Language-level versioning is not yet operational - future code will break unexpectedly. * * * 1. https://doc.rust-lang.org/nightly/rustc/check-cfg.html [↩](https://doc.rust-lang.org/stable/releases.html#fnref1) --- # Rust error codes index - Error codes index Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu Error codes index ================= [](https://doc.rust-lang.org/stable/error_codes/print.html "Print this book") [](https://github.com/rust-lang/rust/ "Git repository") This page lists all the error codes emitted by the Rust compiler. * [E0001](https://doc.rust-lang.org/stable/error_codes/E0001.html) * [E0002](https://doc.rust-lang.org/stable/error_codes/E0002.html) * [E0004](https://doc.rust-lang.org/stable/error_codes/E0004.html) * [E0005](https://doc.rust-lang.org/stable/error_codes/E0005.html) * [E0007](https://doc.rust-lang.org/stable/error_codes/E0007.html) * [E0009](https://doc.rust-lang.org/stable/error_codes/E0009.html) * [E0010](https://doc.rust-lang.org/stable/error_codes/E0010.html) * [E0013](https://doc.rust-lang.org/stable/error_codes/E0013.html) * [E0014](https://doc.rust-lang.org/stable/error_codes/E0014.html) * [E0015](https://doc.rust-lang.org/stable/error_codes/E0015.html) * [E0023](https://doc.rust-lang.org/stable/error_codes/E0023.html) * [E0025](https://doc.rust-lang.org/stable/error_codes/E0025.html) * [E0026](https://doc.rust-lang.org/stable/error_codes/E0026.html) * [E0027](https://doc.rust-lang.org/stable/error_codes/E0027.html) * [E0029](https://doc.rust-lang.org/stable/error_codes/E0029.html) * [E0030](https://doc.rust-lang.org/stable/error_codes/E0030.html) * [E0033](https://doc.rust-lang.org/stable/error_codes/E0033.html) * [E0034](https://doc.rust-lang.org/stable/error_codes/E0034.html) * [E0038](https://doc.rust-lang.org/stable/error_codes/E0038.html) * [E0040](https://doc.rust-lang.org/stable/error_codes/E0040.html) * [E0044](https://doc.rust-lang.org/stable/error_codes/E0044.html) * [E0045](https://doc.rust-lang.org/stable/error_codes/E0045.html) * [E0046](https://doc.rust-lang.org/stable/error_codes/E0046.html) * [E0049](https://doc.rust-lang.org/stable/error_codes/E0049.html) * [E0050](https://doc.rust-lang.org/stable/error_codes/E0050.html) * [E0053](https://doc.rust-lang.org/stable/error_codes/E0053.html) * [E0054](https://doc.rust-lang.org/stable/error_codes/E0054.html) * [E0055](https://doc.rust-lang.org/stable/error_codes/E0055.html) * [E0057](https://doc.rust-lang.org/stable/error_codes/E0057.html) * [E0059](https://doc.rust-lang.org/stable/error_codes/E0059.html) * [E0060](https://doc.rust-lang.org/stable/error_codes/E0060.html) * [E0061](https://doc.rust-lang.org/stable/error_codes/E0061.html) * [E0062](https://doc.rust-lang.org/stable/error_codes/E0062.html) * [E0063](https://doc.rust-lang.org/stable/error_codes/E0063.html) * [E0067](https://doc.rust-lang.org/stable/error_codes/E0067.html) * [E0069](https://doc.rust-lang.org/stable/error_codes/E0069.html) * [E0070](https://doc.rust-lang.org/stable/error_codes/E0070.html) * [E0071](https://doc.rust-lang.org/stable/error_codes/E0071.html) * [E0072](https://doc.rust-lang.org/stable/error_codes/E0072.html) * [E0073](https://doc.rust-lang.org/stable/error_codes/E0073.html) * [E0074](https://doc.rust-lang.org/stable/error_codes/E0074.html) * [E0075](https://doc.rust-lang.org/stable/error_codes/E0075.html) * [E0076](https://doc.rust-lang.org/stable/error_codes/E0076.html) * [E0077](https://doc.rust-lang.org/stable/error_codes/E0077.html) * [E0080](https://doc.rust-lang.org/stable/error_codes/E0080.html) * [E0081](https://doc.rust-lang.org/stable/error_codes/E0081.html) * [E0084](https://doc.rust-lang.org/stable/error_codes/E0084.html) * [E0087](https://doc.rust-lang.org/stable/error_codes/E0087.html) * [E0088](https://doc.rust-lang.org/stable/error_codes/E0088.html) * [E0089](https://doc.rust-lang.org/stable/error_codes/E0089.html) * [E0090](https://doc.rust-lang.org/stable/error_codes/E0090.html) * [E0091](https://doc.rust-lang.org/stable/error_codes/E0091.html) * [E0092](https://doc.rust-lang.org/stable/error_codes/E0092.html) * [E0093](https://doc.rust-lang.org/stable/error_codes/E0093.html) * [E0094](https://doc.rust-lang.org/stable/error_codes/E0094.html) * [E0106](https://doc.rust-lang.org/stable/error_codes/E0106.html) * [E0107](https://doc.rust-lang.org/stable/error_codes/E0107.html) * [E0109](https://doc.rust-lang.org/stable/error_codes/E0109.html) * [E0110](https://doc.rust-lang.org/stable/error_codes/E0110.html) * [E0116](https://doc.rust-lang.org/stable/error_codes/E0116.html) * [E0117](https://doc.rust-lang.org/stable/error_codes/E0117.html) * [E0118](https://doc.rust-lang.org/stable/error_codes/E0118.html) * [E0119](https://doc.rust-lang.org/stable/error_codes/E0119.html) * [E0120](https://doc.rust-lang.org/stable/error_codes/E0120.html) * [E0121](https://doc.rust-lang.org/stable/error_codes/E0121.html) * [E0124](https://doc.rust-lang.org/stable/error_codes/E0124.html) * [E0128](https://doc.rust-lang.org/stable/error_codes/E0128.html) * [E0130](https://doc.rust-lang.org/stable/error_codes/E0130.html) * [E0131](https://doc.rust-lang.org/stable/error_codes/E0131.html) * [E0132](https://doc.rust-lang.org/stable/error_codes/E0132.html) * [E0133](https://doc.rust-lang.org/stable/error_codes/E0133.html) * [E0136](https://doc.rust-lang.org/stable/error_codes/E0136.html) * [E0137](https://doc.rust-lang.org/stable/error_codes/E0137.html) * [E0138](https://doc.rust-lang.org/stable/error_codes/E0138.html) * [E0139](https://doc.rust-lang.org/stable/error_codes/E0139.html) * [E0152](https://doc.rust-lang.org/stable/error_codes/E0152.html) * [E0154](https://doc.rust-lang.org/stable/error_codes/E0154.html) * [E0158](https://doc.rust-lang.org/stable/error_codes/E0158.html) * [E0161](https://doc.rust-lang.org/stable/error_codes/E0161.html) * [E0162](https://doc.rust-lang.org/stable/error_codes/E0162.html) * [E0164](https://doc.rust-lang.org/stable/error_codes/E0164.html) * [E0165](https://doc.rust-lang.org/stable/error_codes/E0165.html) * [E0170](https://doc.rust-lang.org/stable/error_codes/E0170.html) * [E0178](https://doc.rust-lang.org/stable/error_codes/E0178.html) * [E0183](https://doc.rust-lang.org/stable/error_codes/E0183.html) * [E0184](https://doc.rust-lang.org/stable/error_codes/E0184.html) * [E0185](https://doc.rust-lang.org/stable/error_codes/E0185.html) * [E0186](https://doc.rust-lang.org/stable/error_codes/E0186.html) * [E0191](https://doc.rust-lang.org/stable/error_codes/E0191.html) * [E0192](https://doc.rust-lang.org/stable/error_codes/E0192.html) * [E0193](https://doc.rust-lang.org/stable/error_codes/E0193.html) * [E0195](https://doc.rust-lang.org/stable/error_codes/E0195.html) * [E0197](https://doc.rust-lang.org/stable/error_codes/E0197.html) * [E0198](https://doc.rust-lang.org/stable/error_codes/E0198.html) * [E0199](https://doc.rust-lang.org/stable/error_codes/E0199.html) * [E0200](https://doc.rust-lang.org/stable/error_codes/E0200.html) * [E0201](https://doc.rust-lang.org/stable/error_codes/E0201.html) * [E0203](https://doc.rust-lang.org/stable/error_codes/E0203.html) * [E0204](https://doc.rust-lang.org/stable/error_codes/E0204.html) * [E0205](https://doc.rust-lang.org/stable/error_codes/E0205.html) * [E0206](https://doc.rust-lang.org/stable/error_codes/E0206.html) * [E0207](https://doc.rust-lang.org/stable/error_codes/E0207.html) * [E0208](https://doc.rust-lang.org/stable/error_codes/E0208.html) * [E0210](https://doc.rust-lang.org/stable/error_codes/E0210.html) * [E0211](https://doc.rust-lang.org/stable/error_codes/E0211.html) * [E0212](https://doc.rust-lang.org/stable/error_codes/E0212.html) * [E0214](https://doc.rust-lang.org/stable/error_codes/E0214.html) * [E0220](https://doc.rust-lang.org/stable/error_codes/E0220.html) * [E0221](https://doc.rust-lang.org/stable/error_codes/E0221.html) * [E0222](https://doc.rust-lang.org/stable/error_codes/E0222.html) * [E0223](https://doc.rust-lang.org/stable/error_codes/E0223.html) * [E0224](https://doc.rust-lang.org/stable/error_codes/E0224.html) * [E0225](https://doc.rust-lang.org/stable/error_codes/E0225.html) * [E0226](https://doc.rust-lang.org/stable/error_codes/E0226.html) * [E0227](https://doc.rust-lang.org/stable/error_codes/E0227.html) * [E0228](https://doc.rust-lang.org/stable/error_codes/E0228.html) * [E0229](https://doc.rust-lang.org/stable/error_codes/E0229.html) * [E0230](https://doc.rust-lang.org/stable/error_codes/E0230.html) * [E0231](https://doc.rust-lang.org/stable/error_codes/E0231.html) * [E0232](https://doc.rust-lang.org/stable/error_codes/E0232.html) * [E0243](https://doc.rust-lang.org/stable/error_codes/E0243.html) * [E0244](https://doc.rust-lang.org/stable/error_codes/E0244.html) * [E0251](https://doc.rust-lang.org/stable/error_codes/E0251.html) * [E0252](https://doc.rust-lang.org/stable/error_codes/E0252.html) * [E0253](https://doc.rust-lang.org/stable/error_codes/E0253.html) * [E0254](https://doc.rust-lang.org/stable/error_codes/E0254.html) * [E0255](https://doc.rust-lang.org/stable/error_codes/E0255.html) * [E0256](https://doc.rust-lang.org/stable/error_codes/E0256.html) * [E0259](https://doc.rust-lang.org/stable/error_codes/E0259.html) * [E0260](https://doc.rust-lang.org/stable/error_codes/E0260.html) * [E0261](https://doc.rust-lang.org/stable/error_codes/E0261.html) * [E0262](https://doc.rust-lang.org/stable/error_codes/E0262.html) * [E0263](https://doc.rust-lang.org/stable/error_codes/E0263.html) * [E0264](https://doc.rust-lang.org/stable/error_codes/E0264.html) * [E0267](https://doc.rust-lang.org/stable/error_codes/E0267.html) * [E0268](https://doc.rust-lang.org/stable/error_codes/E0268.html) * [E0271](https://doc.rust-lang.org/stable/error_codes/E0271.html) * [E0275](https://doc.rust-lang.org/stable/error_codes/E0275.html) * [E0276](https://doc.rust-lang.org/stable/error_codes/E0276.html) * [E0277](https://doc.rust-lang.org/stable/error_codes/E0277.html) * [E0281](https://doc.rust-lang.org/stable/error_codes/E0281.html) * [E0282](https://doc.rust-lang.org/stable/error_codes/E0282.html) * [E0283](https://doc.rust-lang.org/stable/error_codes/E0283.html) * [E0284](https://doc.rust-lang.org/stable/error_codes/E0284.html) * [E0297](https://doc.rust-lang.org/stable/error_codes/E0297.html) * [E0301](https://doc.rust-lang.org/stable/error_codes/E0301.html) * [E0302](https://doc.rust-lang.org/stable/error_codes/E0302.html) * [E0303](https://doc.rust-lang.org/stable/error_codes/E0303.html) * [E0307](https://doc.rust-lang.org/stable/error_codes/E0307.html) * [E0308](https://doc.rust-lang.org/stable/error_codes/E0308.html) * [E0309](https://doc.rust-lang.org/stable/error_codes/E0309.html) * [E0310](https://doc.rust-lang.org/stable/error_codes/E0310.html) * [E0311](https://doc.rust-lang.org/stable/error_codes/E0311.html) * [E0312](https://doc.rust-lang.org/stable/error_codes/E0312.html) * [E0316](https://doc.rust-lang.org/stable/error_codes/E0316.html) * [E0317](https://doc.rust-lang.org/stable/error_codes/E0317.html) * [E0320](https://doc.rust-lang.org/stable/error_codes/E0320.html) * [E0321](https://doc.rust-lang.org/stable/error_codes/E0321.html) * [E0322](https://doc.rust-lang.org/stable/error_codes/E0322.html) * [E0323](https://doc.rust-lang.org/stable/error_codes/E0323.html) * [E0324](https://doc.rust-lang.org/stable/error_codes/E0324.html) * [E0325](https://doc.rust-lang.org/stable/error_codes/E0325.html) * [E0326](https://doc.rust-lang.org/stable/error_codes/E0326.html) * [E0328](https://doc.rust-lang.org/stable/error_codes/E0328.html) * [E0329](https://doc.rust-lang.org/stable/error_codes/E0329.html) * [E0364](https://doc.rust-lang.org/stable/error_codes/E0364.html) * [E0365](https://doc.rust-lang.org/stable/error_codes/E0365.html) * [E0366](https://doc.rust-lang.org/stable/error_codes/E0366.html) * [E0367](https://doc.rust-lang.org/stable/error_codes/E0367.html) * [E0368](https://doc.rust-lang.org/stable/error_codes/E0368.html) * [E0369](https://doc.rust-lang.org/stable/error_codes/E0369.html) * [E0370](https://doc.rust-lang.org/stable/error_codes/E0370.html) * [E0371](https://doc.rust-lang.org/stable/error_codes/E0371.html) * [E0373](https://doc.rust-lang.org/stable/error_codes/E0373.html) * [E0374](https://doc.rust-lang.org/stable/error_codes/E0374.html) * [E0375](https://doc.rust-lang.org/stable/error_codes/E0375.html) * [E0376](https://doc.rust-lang.org/stable/error_codes/E0376.html) * [E0377](https://doc.rust-lang.org/stable/error_codes/E0377.html) * [E0378](https://doc.rust-lang.org/stable/error_codes/E0378.html) * [E0379](https://doc.rust-lang.org/stable/error_codes/E0379.html) * [E0380](https://doc.rust-lang.org/stable/error_codes/E0380.html) * [E0381](https://doc.rust-lang.org/stable/error_codes/E0381.html) * [E0382](https://doc.rust-lang.org/stable/error_codes/E0382.html) * [E0383](https://doc.rust-lang.org/stable/error_codes/E0383.html) * [E0384](https://doc.rust-lang.org/stable/error_codes/E0384.html) * [E0386](https://doc.rust-lang.org/stable/error_codes/E0386.html) * [E0387](https://doc.rust-lang.org/stable/error_codes/E0387.html) * [E0388](https://doc.rust-lang.org/stable/error_codes/E0388.html) * [E0389](https://doc.rust-lang.org/stable/error_codes/E0389.html) * [E0390](https://doc.rust-lang.org/stable/error_codes/E0390.html) * [E0391](https://doc.rust-lang.org/stable/error_codes/E0391.html) * [E0392](https://doc.rust-lang.org/stable/error_codes/E0392.html) * [E0393](https://doc.rust-lang.org/stable/error_codes/E0393.html) * [E0398](https://doc.rust-lang.org/stable/error_codes/E0398.html) * [E0399](https://doc.rust-lang.org/stable/error_codes/E0399.html) * [E0401](https://doc.rust-lang.org/stable/error_codes/E0401.html) * [E0403](https://doc.rust-lang.org/stable/error_codes/E0403.html) * [E0404](https://doc.rust-lang.org/stable/error_codes/E0404.html) * [E0405](https://doc.rust-lang.org/stable/error_codes/E0405.html) * [E0407](https://doc.rust-lang.org/stable/error_codes/E0407.html) * [E0408](https://doc.rust-lang.org/stable/error_codes/E0408.html) * [E0409](https://doc.rust-lang.org/stable/error_codes/E0409.html) * [E0411](https://doc.rust-lang.org/stable/error_codes/E0411.html) * [E0412](https://doc.rust-lang.org/stable/error_codes/E0412.html) * [E0415](https://doc.rust-lang.org/stable/error_codes/E0415.html) * [E0416](https://doc.rust-lang.org/stable/error_codes/E0416.html) * [E0422](https://doc.rust-lang.org/stable/error_codes/E0422.html) * [E0423](https://doc.rust-lang.org/stable/error_codes/E0423.html) * [E0424](https://doc.rust-lang.org/stable/error_codes/E0424.html) * [E0425](https://doc.rust-lang.org/stable/error_codes/E0425.html) * [E0426](https://doc.rust-lang.org/stable/error_codes/E0426.html) * [E0428](https://doc.rust-lang.org/stable/error_codes/E0428.html) * [E0429](https://doc.rust-lang.org/stable/error_codes/E0429.html) * [E0430](https://doc.rust-lang.org/stable/error_codes/E0430.html) * [E0431](https://doc.rust-lang.org/stable/error_codes/E0431.html) * [E0432](https://doc.rust-lang.org/stable/error_codes/E0432.html) * [E0433](https://doc.rust-lang.org/stable/error_codes/E0433.html) * [E0434](https://doc.rust-lang.org/stable/error_codes/E0434.html) * [E0435](https://doc.rust-lang.org/stable/error_codes/E0435.html) * [E0436](https://doc.rust-lang.org/stable/error_codes/E0436.html) * [E0437](https://doc.rust-lang.org/stable/error_codes/E0437.html) * [E0438](https://doc.rust-lang.org/stable/error_codes/E0438.html) * [E0439](https://doc.rust-lang.org/stable/error_codes/E0439.html) * [E0445](https://doc.rust-lang.org/stable/error_codes/E0445.html) * [E0446](https://doc.rust-lang.org/stable/error_codes/E0446.html) * [E0447](https://doc.rust-lang.org/stable/error_codes/E0447.html) * [E0448](https://doc.rust-lang.org/stable/error_codes/E0448.html) * [E0449](https://doc.rust-lang.org/stable/error_codes/E0449.html) * [E0451](https://doc.rust-lang.org/stable/error_codes/E0451.html) * [E0452](https://doc.rust-lang.org/stable/error_codes/E0452.html) * [E0453](https://doc.rust-lang.org/stable/error_codes/E0453.html) * [E0454](https://doc.rust-lang.org/stable/error_codes/E0454.html) * [E0455](https://doc.rust-lang.org/stable/error_codes/E0455.html) * [E0457](https://doc.rust-lang.org/stable/error_codes/E0457.html) * [E0458](https://doc.rust-lang.org/stable/error_codes/E0458.html) * [E0459](https://doc.rust-lang.org/stable/error_codes/E0459.html) * [E0460](https://doc.rust-lang.org/stable/error_codes/E0460.html) * [E0461](https://doc.rust-lang.org/stable/error_codes/E0461.html) * [E0462](https://doc.rust-lang.org/stable/error_codes/E0462.html) * [E0463](https://doc.rust-lang.org/stable/error_codes/E0463.html) * [E0464](https://doc.rust-lang.org/stable/error_codes/E0464.html) * [E0466](https://doc.rust-lang.org/stable/error_codes/E0466.html) * [E0468](https://doc.rust-lang.org/stable/error_codes/E0468.html) * [E0469](https://doc.rust-lang.org/stable/error_codes/E0469.html) * [E0472](https://doc.rust-lang.org/stable/error_codes/E0472.html) * [E0476](https://doc.rust-lang.org/stable/error_codes/E0476.html) * [E0477](https://doc.rust-lang.org/stable/error_codes/E0477.html) * [E0478](https://doc.rust-lang.org/stable/error_codes/E0478.html) * [E0482](https://doc.rust-lang.org/stable/error_codes/E0482.html) * [E0491](https://doc.rust-lang.org/stable/error_codes/E0491.html) * [E0492](https://doc.rust-lang.org/stable/error_codes/E0492.html) * [E0493](https://doc.rust-lang.org/stable/error_codes/E0493.html) * [E0495](https://doc.rust-lang.org/stable/error_codes/E0495.html) * [E0496](https://doc.rust-lang.org/stable/error_codes/E0496.html) * [E0497](https://doc.rust-lang.org/stable/error_codes/E0497.html) * [E0498](https://doc.rust-lang.org/stable/error_codes/E0498.html) * [E0499](https://doc.rust-lang.org/stable/error_codes/E0499.html) * [E0500](https://doc.rust-lang.org/stable/error_codes/E0500.html) * [E0501](https://doc.rust-lang.org/stable/error_codes/E0501.html) * [E0502](https://doc.rust-lang.org/stable/error_codes/E0502.html) * [E0503](https://doc.rust-lang.org/stable/error_codes/E0503.html) * [E0504](https://doc.rust-lang.org/stable/error_codes/E0504.html) * [E0505](https://doc.rust-lang.org/stable/error_codes/E0505.html) * [E0506](https://doc.rust-lang.org/stable/error_codes/E0506.html) * [E0507](https://doc.rust-lang.org/stable/error_codes/E0507.html) * [E0508](https://doc.rust-lang.org/stable/error_codes/E0508.html) * [E0509](https://doc.rust-lang.org/stable/error_codes/E0509.html) * [E0510](https://doc.rust-lang.org/stable/error_codes/E0510.html) * [E0511](https://doc.rust-lang.org/stable/error_codes/E0511.html) * [E0512](https://doc.rust-lang.org/stable/error_codes/E0512.html) * [E0514](https://doc.rust-lang.org/stable/error_codes/E0514.html) * [E0515](https://doc.rust-lang.org/stable/error_codes/E0515.html) * [E0516](https://doc.rust-lang.org/stable/error_codes/E0516.html) * [E0517](https://doc.rust-lang.org/stable/error_codes/E0517.html) * [E0518](https://doc.rust-lang.org/stable/error_codes/E0518.html) * [E0519](https://doc.rust-lang.org/stable/error_codes/E0519.html) * [E0520](https://doc.rust-lang.org/stable/error_codes/E0520.html) * [E0521](https://doc.rust-lang.org/stable/error_codes/E0521.html) * [E0522](https://doc.rust-lang.org/stable/error_codes/E0522.html) * [E0523](https://doc.rust-lang.org/stable/error_codes/E0523.html) * [E0524](https://doc.rust-lang.org/stable/error_codes/E0524.html) * [E0525](https://doc.rust-lang.org/stable/error_codes/E0525.html) * [E0527](https://doc.rust-lang.org/stable/error_codes/E0527.html) * [E0528](https://doc.rust-lang.org/stable/error_codes/E0528.html) * [E0529](https://doc.rust-lang.org/stable/error_codes/E0529.html) * [E0530](https://doc.rust-lang.org/stable/error_codes/E0530.html) * [E0531](https://doc.rust-lang.org/stable/error_codes/E0531.html) * [E0532](https://doc.rust-lang.org/stable/error_codes/E0532.html) * [E0533](https://doc.rust-lang.org/stable/error_codes/E0533.html) * [E0534](https://doc.rust-lang.org/stable/error_codes/E0534.html) * [E0535](https://doc.rust-lang.org/stable/error_codes/E0535.html) * [E0536](https://doc.rust-lang.org/stable/error_codes/E0536.html) * [E0537](https://doc.rust-lang.org/stable/error_codes/E0537.html) * [E0538](https://doc.rust-lang.org/stable/error_codes/E0538.html) * [E0539](https://doc.rust-lang.org/stable/error_codes/E0539.html) * [E0541](https://doc.rust-lang.org/stable/error_codes/E0541.html) * [E0542](https://doc.rust-lang.org/stable/error_codes/E0542.html) * [E0543](https://doc.rust-lang.org/stable/error_codes/E0543.html) * [E0544](https://doc.rust-lang.org/stable/error_codes/E0544.html) * [E0545](https://doc.rust-lang.org/stable/error_codes/E0545.html) * [E0546](https://doc.rust-lang.org/stable/error_codes/E0546.html) * [E0547](https://doc.rust-lang.org/stable/error_codes/E0547.html) * [E0549](https://doc.rust-lang.org/stable/error_codes/E0549.html) * [E0550](https://doc.rust-lang.org/stable/error_codes/E0550.html) * [E0551](https://doc.rust-lang.org/stable/error_codes/E0551.html) * [E0552](https://doc.rust-lang.org/stable/error_codes/E0552.html) * [E0554](https://doc.rust-lang.org/stable/error_codes/E0554.html) * [E0556](https://doc.rust-lang.org/stable/error_codes/E0556.html) * [E0557](https://doc.rust-lang.org/stable/error_codes/E0557.html) * [E0559](https://doc.rust-lang.org/stable/error_codes/E0559.html) * [E0560](https://doc.rust-lang.org/stable/error_codes/E0560.html) * [E0561](https://doc.rust-lang.org/stable/error_codes/E0561.html) * [E0562](https://doc.rust-lang.org/stable/error_codes/E0562.html) * [E0565](https://doc.rust-lang.org/stable/error_codes/E0565.html) * [E0566](https://doc.rust-lang.org/stable/error_codes/E0566.html) * [E0567](https://doc.rust-lang.org/stable/error_codes/E0567.html) * [E0568](https://doc.rust-lang.org/stable/error_codes/E0568.html) * [E0569](https://doc.rust-lang.org/stable/error_codes/E0569.html) * [E0570](https://doc.rust-lang.org/stable/error_codes/E0570.html) * [E0571](https://doc.rust-lang.org/stable/error_codes/E0571.html) * [E0572](https://doc.rust-lang.org/stable/error_codes/E0572.html) * [E0573](https://doc.rust-lang.org/stable/error_codes/E0573.html) * [E0574](https://doc.rust-lang.org/stable/error_codes/E0574.html) * [E0575](https://doc.rust-lang.org/stable/error_codes/E0575.html) * [E0576](https://doc.rust-lang.org/stable/error_codes/E0576.html) * [E0577](https://doc.rust-lang.org/stable/error_codes/E0577.html) * [E0578](https://doc.rust-lang.org/stable/error_codes/E0578.html) * [E0579](https://doc.rust-lang.org/stable/error_codes/E0579.html) * [E0580](https://doc.rust-lang.org/stable/error_codes/E0580.html) * [E0581](https://doc.rust-lang.org/stable/error_codes/E0581.html) * [E0582](https://doc.rust-lang.org/stable/error_codes/E0582.html) * [E0583](https://doc.rust-lang.org/stable/error_codes/E0583.html) * [E0584](https://doc.rust-lang.org/stable/error_codes/E0584.html) * [E0585](https://doc.rust-lang.org/stable/error_codes/E0585.html) * [E0586](https://doc.rust-lang.org/stable/error_codes/E0586.html) * [E0587](https://doc.rust-lang.org/stable/error_codes/E0587.html) * [E0588](https://doc.rust-lang.org/stable/error_codes/E0588.html) * [E0589](https://doc.rust-lang.org/stable/error_codes/E0589.html) * [E0590](https://doc.rust-lang.org/stable/error_codes/E0590.html) * [E0591](https://doc.rust-lang.org/stable/error_codes/E0591.html) * [E0592](https://doc.rust-lang.org/stable/error_codes/E0592.html) * [E0593](https://doc.rust-lang.org/stable/error_codes/E0593.html) * [E0594](https://doc.rust-lang.org/stable/error_codes/E0594.html) * [E0595](https://doc.rust-lang.org/stable/error_codes/E0595.html) * [E0596](https://doc.rust-lang.org/stable/error_codes/E0596.html) * [E0597](https://doc.rust-lang.org/stable/error_codes/E0597.html) * [E0599](https://doc.rust-lang.org/stable/error_codes/E0599.html) * [E0600](https://doc.rust-lang.org/stable/error_codes/E0600.html) * [E0601](https://doc.rust-lang.org/stable/error_codes/E0601.html) * [E0602](https://doc.rust-lang.org/stable/error_codes/E0602.html) * [E0603](https://doc.rust-lang.org/stable/error_codes/E0603.html) * [E0604](https://doc.rust-lang.org/stable/error_codes/E0604.html) * [E0605](https://doc.rust-lang.org/stable/error_codes/E0605.html) * [E0606](https://doc.rust-lang.org/stable/error_codes/E0606.html) * [E0607](https://doc.rust-lang.org/stable/error_codes/E0607.html) * [E0608](https://doc.rust-lang.org/stable/error_codes/E0608.html) * [E0609](https://doc.rust-lang.org/stable/error_codes/E0609.html) * [E0610](https://doc.rust-lang.org/stable/error_codes/E0610.html) * [E0614](https://doc.rust-lang.org/stable/error_codes/E0614.html) * [E0615](https://doc.rust-lang.org/stable/error_codes/E0615.html) * [E0616](https://doc.rust-lang.org/stable/error_codes/E0616.html) * [E0617](https://doc.rust-lang.org/stable/error_codes/E0617.html) * [E0618](https://doc.rust-lang.org/stable/error_codes/E0618.html) * [E0619](https://doc.rust-lang.org/stable/error_codes/E0619.html) * [E0620](https://doc.rust-lang.org/stable/error_codes/E0620.html) * [E0621](https://doc.rust-lang.org/stable/error_codes/E0621.html) * [E0622](https://doc.rust-lang.org/stable/error_codes/E0622.html) * [E0623](https://doc.rust-lang.org/stable/error_codes/E0623.html) * [E0624](https://doc.rust-lang.org/stable/error_codes/E0624.html) * [E0625](https://doc.rust-lang.org/stable/error_codes/E0625.html) * [E0626](https://doc.rust-lang.org/stable/error_codes/E0626.html) * [E0627](https://doc.rust-lang.org/stable/error_codes/E0627.html) * [E0628](https://doc.rust-lang.org/stable/error_codes/E0628.html) * [E0631](https://doc.rust-lang.org/stable/error_codes/E0631.html) * [E0632](https://doc.rust-lang.org/stable/error_codes/E0632.html) * [E0633](https://doc.rust-lang.org/stable/error_codes/E0633.html) * [E0634](https://doc.rust-lang.org/stable/error_codes/E0634.html) * [E0635](https://doc.rust-lang.org/stable/error_codes/E0635.html) * [E0636](https://doc.rust-lang.org/stable/error_codes/E0636.html) * [E0637](https://doc.rust-lang.org/stable/error_codes/E0637.html) * [E0638](https://doc.rust-lang.org/stable/error_codes/E0638.html) * [E0639](https://doc.rust-lang.org/stable/error_codes/E0639.html) * [E0640](https://doc.rust-lang.org/stable/error_codes/E0640.html) * [E0641](https://doc.rust-lang.org/stable/error_codes/E0641.html) * [E0642](https://doc.rust-lang.org/stable/error_codes/E0642.html) * [E0643](https://doc.rust-lang.org/stable/error_codes/E0643.html) * [E0644](https://doc.rust-lang.org/stable/error_codes/E0644.html) * [E0646](https://doc.rust-lang.org/stable/error_codes/E0646.html) * [E0647](https://doc.rust-lang.org/stable/error_codes/E0647.html) * [E0648](https://doc.rust-lang.org/stable/error_codes/E0648.html) * [E0657](https://doc.rust-lang.org/stable/error_codes/E0657.html) * [E0658](https://doc.rust-lang.org/stable/error_codes/E0658.html) * [E0659](https://doc.rust-lang.org/stable/error_codes/E0659.html) * [E0660](https://doc.rust-lang.org/stable/error_codes/E0660.html) * [E0661](https://doc.rust-lang.org/stable/error_codes/E0661.html) * [E0662](https://doc.rust-lang.org/stable/error_codes/E0662.html) * [E0663](https://doc.rust-lang.org/stable/error_codes/E0663.html) * [E0664](https://doc.rust-lang.org/stable/error_codes/E0664.html) * [E0665](https://doc.rust-lang.org/stable/error_codes/E0665.html) * [E0666](https://doc.rust-lang.org/stable/error_codes/E0666.html) * [E0667](https://doc.rust-lang.org/stable/error_codes/E0667.html) * [E0668](https://doc.rust-lang.org/stable/error_codes/E0668.html) * [E0669](https://doc.rust-lang.org/stable/error_codes/E0669.html) * [E0670](https://doc.rust-lang.org/stable/error_codes/E0670.html) * [E0671](https://doc.rust-lang.org/stable/error_codes/E0671.html) * [E0687](https://doc.rust-lang.org/stable/error_codes/E0687.html) * [E0688](https://doc.rust-lang.org/stable/error_codes/E0688.html) * [E0689](https://doc.rust-lang.org/stable/error_codes/E0689.html) * [E0690](https://doc.rust-lang.org/stable/error_codes/E0690.html) * [E0691](https://doc.rust-lang.org/stable/error_codes/E0691.html) * [E0692](https://doc.rust-lang.org/stable/error_codes/E0692.html) * [E0693](https://doc.rust-lang.org/stable/error_codes/E0693.html) * [E0695](https://doc.rust-lang.org/stable/error_codes/E0695.html) * [E0696](https://doc.rust-lang.org/stable/error_codes/E0696.html) * [E0697](https://doc.rust-lang.org/stable/error_codes/E0697.html) * [E0698](https://doc.rust-lang.org/stable/error_codes/E0698.html) * [E0699](https://doc.rust-lang.org/stable/error_codes/E0699.html) * [E0700](https://doc.rust-lang.org/stable/error_codes/E0700.html) * [E0701](https://doc.rust-lang.org/stable/error_codes/E0701.html) * [E0703](https://doc.rust-lang.org/stable/error_codes/E0703.html) * [E0704](https://doc.rust-lang.org/stable/error_codes/E0704.html) * [E0705](https://doc.rust-lang.org/stable/error_codes/E0705.html) * [E0706](https://doc.rust-lang.org/stable/error_codes/E0706.html) * [E0708](https://doc.rust-lang.org/stable/error_codes/E0708.html) * [E0710](https://doc.rust-lang.org/stable/error_codes/E0710.html) * [E0712](https://doc.rust-lang.org/stable/error_codes/E0712.html) * [E0713](https://doc.rust-lang.org/stable/error_codes/E0713.html) * [E0714](https://doc.rust-lang.org/stable/error_codes/E0714.html) * [E0715](https://doc.rust-lang.org/stable/error_codes/E0715.html) * [E0716](https://doc.rust-lang.org/stable/error_codes/E0716.html) * [E0711](https://doc.rust-lang.org/stable/error_codes/E0711.html) * [E0717](https://doc.rust-lang.org/stable/error_codes/E0717.html) * [E0718](https://doc.rust-lang.org/stable/error_codes/E0718.html) * [E0719](https://doc.rust-lang.org/stable/error_codes/E0719.html) * [E0720](https://doc.rust-lang.org/stable/error_codes/E0720.html) * [E0722](https://doc.rust-lang.org/stable/error_codes/E0722.html) * [E0724](https://doc.rust-lang.org/stable/error_codes/E0724.html) * [E0725](https://doc.rust-lang.org/stable/error_codes/E0725.html) * [E0726](https://doc.rust-lang.org/stable/error_codes/E0726.html) * [E0727](https://doc.rust-lang.org/stable/error_codes/E0727.html) * [E0728](https://doc.rust-lang.org/stable/error_codes/E0728.html) * [E0729](https://doc.rust-lang.org/stable/error_codes/E0729.html) * [E0730](https://doc.rust-lang.org/stable/error_codes/E0730.html) * [E0731](https://doc.rust-lang.org/stable/error_codes/E0731.html) * [E0732](https://doc.rust-lang.org/stable/error_codes/E0732.html) * [E0733](https://doc.rust-lang.org/stable/error_codes/E0733.html) * [E0734](https://doc.rust-lang.org/stable/error_codes/E0734.html) * [E0735](https://doc.rust-lang.org/stable/error_codes/E0735.html) * [E0736](https://doc.rust-lang.org/stable/error_codes/E0736.html) * [E0737](https://doc.rust-lang.org/stable/error_codes/E0737.html) * [E0739](https://doc.rust-lang.org/stable/error_codes/E0739.html) * [E0740](https://doc.rust-lang.org/stable/error_codes/E0740.html) * [E0741](https://doc.rust-lang.org/stable/error_codes/E0741.html) * [E0742](https://doc.rust-lang.org/stable/error_codes/E0742.html) * [E0743](https://doc.rust-lang.org/stable/error_codes/E0743.html) * [E0744](https://doc.rust-lang.org/stable/error_codes/E0744.html) * [E0745](https://doc.rust-lang.org/stable/error_codes/E0745.html) * [E0746](https://doc.rust-lang.org/stable/error_codes/E0746.html) * [E0747](https://doc.rust-lang.org/stable/error_codes/E0747.html) * [E0748](https://doc.rust-lang.org/stable/error_codes/E0748.html) * [E0749](https://doc.rust-lang.org/stable/error_codes/E0749.html) * [E0750](https://doc.rust-lang.org/stable/error_codes/E0750.html) * [E0751](https://doc.rust-lang.org/stable/error_codes/E0751.html) * [E0752](https://doc.rust-lang.org/stable/error_codes/E0752.html) * [E0753](https://doc.rust-lang.org/stable/error_codes/E0753.html) * [E0754](https://doc.rust-lang.org/stable/error_codes/E0754.html) * [E0755](https://doc.rust-lang.org/stable/error_codes/E0755.html) * [E0756](https://doc.rust-lang.org/stable/error_codes/E0756.html) * [E0757](https://doc.rust-lang.org/stable/error_codes/E0757.html) * [E0758](https://doc.rust-lang.org/stable/error_codes/E0758.html) * [E0759](https://doc.rust-lang.org/stable/error_codes/E0759.html) * [E0760](https://doc.rust-lang.org/stable/error_codes/E0760.html) * [E0761](https://doc.rust-lang.org/stable/error_codes/E0761.html) * [E0762](https://doc.rust-lang.org/stable/error_codes/E0762.html) * [E0763](https://doc.rust-lang.org/stable/error_codes/E0763.html) * [E0764](https://doc.rust-lang.org/stable/error_codes/E0764.html) * [E0765](https://doc.rust-lang.org/stable/error_codes/E0765.html) * [E0766](https://doc.rust-lang.org/stable/error_codes/E0766.html) * [E0767](https://doc.rust-lang.org/stable/error_codes/E0767.html) * [E0768](https://doc.rust-lang.org/stable/error_codes/E0768.html) * [E0769](https://doc.rust-lang.org/stable/error_codes/E0769.html) * [E0770](https://doc.rust-lang.org/stable/error_codes/E0770.html) * [E0771](https://doc.rust-lang.org/stable/error_codes/E0771.html) * [E0772](https://doc.rust-lang.org/stable/error_codes/E0772.html) * [E0773](https://doc.rust-lang.org/stable/error_codes/E0773.html) * [E0774](https://doc.rust-lang.org/stable/error_codes/E0774.html) * [E0775](https://doc.rust-lang.org/stable/error_codes/E0775.html) * [E0776](https://doc.rust-lang.org/stable/error_codes/E0776.html) * [E0777](https://doc.rust-lang.org/stable/error_codes/E0777.html) * [E0778](https://doc.rust-lang.org/stable/error_codes/E0778.html) * [E0779](https://doc.rust-lang.org/stable/error_codes/E0779.html) * [E0780](https://doc.rust-lang.org/stable/error_codes/E0780.html) * [E0781](https://doc.rust-lang.org/stable/error_codes/E0781.html) * [E0782](https://doc.rust-lang.org/stable/error_codes/E0782.html) * [E0783](https://doc.rust-lang.org/stable/error_codes/E0783.html) * [E0784](https://doc.rust-lang.org/stable/error_codes/E0784.html) * [E0785](https://doc.rust-lang.org/stable/error_codes/E0785.html) * [E0786](https://doc.rust-lang.org/stable/error_codes/E0786.html) * [E0787](https://doc.rust-lang.org/stable/error_codes/E0787.html) * [E0788](https://doc.rust-lang.org/stable/error_codes/E0788.html) * [E0789](https://doc.rust-lang.org/stable/error_codes/E0789.html) * [E0790](https://doc.rust-lang.org/stable/error_codes/E0790.html) * [E0791](https://doc.rust-lang.org/stable/error_codes/E0791.html) * [E0792](https://doc.rust-lang.org/stable/error_codes/E0792.html) * [E0793](https://doc.rust-lang.org/stable/error_codes/E0793.html) * [E0794](https://doc.rust-lang.org/stable/error_codes/E0794.html) * [E0795](https://doc.rust-lang.org/stable/error_codes/E0795.html) * [E0796](https://doc.rust-lang.org/stable/error_codes/E0796.html) * [E0797](https://doc.rust-lang.org/stable/error_codes/E0797.html) * [E0798](https://doc.rust-lang.org/stable/error_codes/E0798.html) * [E0799](https://doc.rust-lang.org/stable/error_codes/E0799.html) * [E0800](https://doc.rust-lang.org/stable/error_codes/E0800.html) * [E0801](https://doc.rust-lang.org/stable/error_codes/E0801.html) * [E0802](https://doc.rust-lang.org/stable/error_codes/E0802.html) * [E0803](https://doc.rust-lang.org/stable/error_codes/E0803.html) * [E0804](https://doc.rust-lang.org/stable/error_codes/E0804.html) * [E0805](https://doc.rust-lang.org/stable/error_codes/E0805.html) --- # The Unstable Book - The Rust Unstable Book Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Unstable Book ====================== [](https://doc.rust-lang.org/stable/unstable-book/print.html "Print this book") [](https://github.com/rust-lang/rust/tree/master/src/doc/unstable-book "Git repository") [](https://github.com/rust-lang/rust/edit/master/src/doc/unstable-book/src/the-unstable-book.md "Suggest an edit") Welcome to the Unstable Book! This book consists of a number of chapters, each one organized by a "feature flag." That is, when using an unstable feature of Rust, you must use a flag, like this: `#![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::{Coroutine, CoroutineState}; use std::pin::Pin; fn main() { let mut coroutine = #[coroutine] || { yield 1; return "foo" }; match Pin::new(&mut coroutine).resume(()) { CoroutineState::Yielded(1) => {} _ => panic!("unexpected value from resume"), } match Pin::new(&mut coroutine).resume(()) { CoroutineState::Complete("foo") => {} _ => panic!("unexpected value from resume"), } }` The `coroutines` feature [has a chapter](https://doc.rust-lang.org/stable/unstable-book/language-features/coroutines.html) describing how to use it. Because this documentation relates to unstable features, we make no guarantees that what is contained here is accurate or up to date. It's developed on a best-effort basis. Each page will have a link to its tracking issue with the latest developments; you might want to check those as well. --- # Settings [All](https://doc.rust-lang.org/stable/settings.html#) ------------------------------------------------------- Rustdoc settings ================ [Back](javascript:void(0)) --- # Help [All](https://doc.rust-lang.org/stable/help.html#) --------------------------------------------------- Rustdoc help ============ [Back](javascript:void(0)) --- # Control Scope and Privacy with Modules - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") In this section, we’ll talk about modules and other parts of the module system, namely _paths_, which allow you to name items; the `use` keyword that brings a path into scope; and the `pub` keyword to make items public. We’ll also discuss the `as` keyword, external packages, and the glob operator. Before we get to the details of modules and paths, here we provide a quick reference on how modules, paths, the `use` keyword, and the `pub` keyword work in the compiler, and how most developers organize their code. We’ll be going through examples of each of these rules throughout this chapter, but this is a great place to refer to as a reminder of how modules work. * **Start from the crate root**: When compiling a crate, the compiler first looks in the crate root file (usually _src/lib.rs_ for a library crate and _src/main.rs_ for a binary crate) for code to compile. * **Declaring modules**: In the crate root file, you can declare new modules; say you declare a “garden” module with `mod garden;`. The compiler will look for the module’s code in these places: * Inline, within curly brackets that replace the semicolon following `mod garden` * In the file _src/garden.rs_ * In the file _src/garden/mod.rs_ * **Declaring submodules**: In any file other than the crate root, you can declare submodules. For example, you might declare `mod vegetables;` in _src/garden.rs_. The compiler will look for the submodule’s code within the directory named for the parent module in these places: * Inline, directly following `mod vegetables`, within curly brackets instead of the semicolon * In the file _src/garden/vegetables.rs_ * In the file _src/garden/vegetables/mod.rs_ * **Paths to code in modules**: Once a module is part of your crate, you can refer to code in that module from anywhere else in that same crate, as long as the privacy rules allow, using the path to the code. For example, an `Asparagus` type in the garden vegetables module would be found at `crate::garden::vegetables::Asparagus`. * **Private vs. public**: Code within a module is private from its parent modules by default. To make a module public, declare it with `pub mod` instead of `mod`. To make items within a public module public as well, use `pub` before their declarations. * **The `use` keyword**: Within a scope, the `use` keyword creates shortcuts to items to reduce repetition of long paths. In any scope that can refer to `crate::garden::vegetables::Asparagus`, you can create a shortcut with `use crate::garden::vegetables::Asparagus;`, and from then on you only need to write `Asparagus` to make use of that type in the scope. Here, we create a binary crate named `backyard` that illustrates these rules. The crate’s directory, also named _backyard_, contains these files and directories: backyard ├── Cargo.lock ├── Cargo.toml └── src ├── garden │   └── vegetables.rs ├── garden.rs └── main.rs The crate root file in this case is _src/main.rs_, and it contains: Filename: src/main.rs use crate::garden::vegetables::Asparagus; pub mod garden; fn main() { let plant = Asparagus {}; println!("I'm growing {plant:?}!"); } The `pub mod garden;` line tells the compiler to include the code it finds in _src/garden.rs_, which is: Filename: src/garden.rs pub mod vegetables; Here, `pub mod vegetables;` means the code in _src/garden/vegetables.rs_ is included too. That code is: #[derive(Debug)] pub struct Asparagus {} Now let’s get into the details of these rules and demonstrate them in action! _Modules_ let us organize code within a crate for readability and easy reuse. Modules also allow us to control the _privacy_ of items because code within a module is private by default. Private items are internal implementation details not available for outside use. We can choose to make modules and the items within them public, which exposes them to allow external code to use and depend on them. As an example, let’s write a library crate that provides the functionality of a restaurant. We’ll define the signatures of functions but leave their bodies empty to concentrate on the organization of the code rather than the implementation of a restaurant. In the restaurant industry, some parts of a restaurant are referred to as front of house and others as back of house. _Front of house_ is where customers are; this encompasses where the hosts seat customers, servers take orders and payment, and bartenders make drinks. _Back of house_ is where the chefs and cooks work in the kitchen, dishwashers clean up, and managers do administrative work. To structure our crate in this way, we can organize its functions into nested modules. Create a new library named `restaurant` by running `cargo new restaurant --lib`. Then, enter the code in Listing 7-1 into _src/lib.rs_ to define some modules and function signatures; this code is the front of house section. Filename: src/lib.rs mod front_of_house { mod hosting { fn add_to_waitlist() {} fn seat_at_table() {} } mod serving { fn take_order() {} fn serve_order() {} fn take_payment() {} } } [Listing 7-1](https://doc.rust-lang.org/stable/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#listing-7-1) : A `front_of_house` module containing other modules that then contain functions We define a module with the `mod` keyword followed by the name of the module (in this case, `front_of_house`). The body of the module then goes inside curly brackets. Inside modules, we can place other modules, as in this case with the modules `hosting` and `serving`. Modules can also hold definitions for other items, such as structs, enums, constants, traits, and as in Listing 7-1, functions. By using modules, we can group related definitions together and name why they’re related. Programmers using this code can navigate the code based on the groups rather than having to read through all the definitions, making it easier to find the definitions relevant to them. Programmers adding new functionality to this code would know where to place the code to keep the program organized. Earlier, we mentioned that _src/main.rs_ and _src/lib.rs_ are called _crate roots_\_. The reason for their name is that the contents of either of these two files form a module named `crate` at the root of the crate’s module structure, known as the _module tree_. Listing 7-2 shows the module tree for the structure in Listing 7-1. crate └── front_of_house ├── hosting │ ├── add_to_waitlist │ └── seat_at_table └── serving ├── take_order ├── serve_order └── take_payment [Listing 7-2](https://doc.rust-lang.org/stable/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#listing-7-2) : The module tree for the code in Listing 7-1 This tree shows how some of the modules nest inside other modules; for example, `hosting` nests inside `front_of_house`. The tree also shows that some modules are _siblings_, meaning they’re defined in the same module; `hosting` and `serving` are siblings defined within `front_of_house`. If module A is contained inside module B, we say that module A is the _child_ of module B and that module B is the _parent_ of module A. Notice that the entire module tree is rooted under the implicit module named `crate`. The module tree might remind you of the filesystem’s directory tree on your computer; this is a very apt comparison! Just like directories in a filesystem, you use modules to organize your code. And just like files in a directory, we need a way to find our modules. --- # std_detect - Rust [Crate std\_detect](https://doc.rust-lang.org/stable/std_detect/index.html#) ----------------------------------------------------------------------------- Crate std\_detect Copy item path ================================ [Source](https://doc.rust-lang.org/stable/src/std_detect/lib.rs.html#1-36) 🔬This is a nightly-only experimental API. (`stdarch_internal`) Expand description Run-time feature detection for the Rust standard library. To detect whether a feature is enabled in the system running the binary use one of the appropriate macro for the target: * `x86` and `x86_64`: [`is_x86_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_x86_feature_detected.html "macro std_detect::is_x86_feature_detected") * `arm`: [`is_arm_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_arm_feature_detected.html "macro std_detect::is_arm_feature_detected") * `aarch64`: [`is_aarch64_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_aarch64_feature_detected.html "macro std_detect::is_aarch64_feature_detected") * `riscv`: [`is_riscv_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_riscv_feature_detected.html "macro std_detect::is_riscv_feature_detected") * `mips`: [`is_mips_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_mips_feature_detected.html "macro std_detect::is_mips_feature_detected") * `mips64`: [`is_mips64_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_mips64_feature_detected.html "macro std_detect::is_mips64_feature_detected") * `powerpc`: [`is_powerpc_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_powerpc_feature_detected.html "macro std_detect::is_powerpc_feature_detected") * `powerpc64`: [`is_powerpc64_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_powerpc64_feature_detected.html "macro std_detect::is_powerpc64_feature_detected") * `loongarch`: [`is_loongarch_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_loongarch_feature_detected.html "macro std_detect::is_loongarch_feature_detected") * `s390x`: [`is_s390x_feature_detected`](https://doc.rust-lang.org/stable/std_detect/macro.is_s390x_feature_detected.html "macro std_detect::is_s390x_feature_detected") Macros[§](https://doc.rust-lang.org/stable/std_detect/index.html#macros) ------------------------------------------------------------------------- [detect\_feature](https://doc.rust-lang.org/stable/std_detect/macro.detect_feature.html "macro std_detect::detect_feature") Experimental [is\_aarch64\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_aarch64_feature_detected.html "macro std_detect::is_aarch64_feature_detected") ExperimentalAArch64 or `target_arch=arm64ec` This macro tests, at runtime, whether an `aarch64` feature is enabled on aarch64 platforms. Currently most features are only supported on linux-based platforms. [is\_arm\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_arm_feature_detected.html "macro std_detect::is_arm_feature_detected") ExperimentalARM Checks if `arm` feature is enabled. [is\_loongarch\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_loongarch_feature_detected.html "macro std_detect::is_loongarch_feature_detected") ExperimentalLoongArch LA32 or LoongArch LA64 Checks if `loongarch` feature is enabled. Supported arguments are: [is\_mips64\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_mips64_feature_detected.html "macro std_detect::is_mips64_feature_detected") ExperimentalMIPS-64 Checks if `mips64` feature is enabled. [is\_mips\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_mips_feature_detected.html "macro std_detect::is_mips_feature_detected") ExperimentalMIPS Checks if `mips` feature is enabled. [is\_powerpc64\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_powerpc64_feature_detected.html "macro std_detect::is_powerpc64_feature_detected") ExperimentalPowerPC-64 Checks if `powerpc` feature is enabled. [is\_powerpc\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_powerpc_feature_detected.html "macro std_detect::is_powerpc_feature_detected") ExperimentalPowerPC Checks if `powerpc` feature is enabled. [is\_riscv\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_riscv_feature_detected.html "macro std_detect::is_riscv_feature_detected") ExperimentalRISC-V RV32 or RISC-V RV64 A macro to test at _runtime_ whether instruction sets are available on RISC-V platforms. [is\_s390x\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_s390x_feature_detected.html "macro std_detect::is_s390x_feature_detected") Experimentals390x Checks if `s390x` feature is enabled. [is\_x86\_feature\_detected](https://doc.rust-lang.org/stable/std_detect/macro.is_x86_feature_detected.html "macro std_detect::is_x86_feature_detected") Experimentalx86 or x86-64 A macro to test at _runtime_ whether a CPU feature is available on x86/x86-64 platforms. --- # Data Types - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Every value in Rust is of a certain _data type_, which tells Rust what kind of data is being specified so that it knows how to work with that data. We’ll look at two data type subsets: scalar and compound. Keep in mind that Rust is a _statically typed_ language, which means that it must know the types of all variables at compile time. The compiler can usually infer what type we want to use based on the value and how we use it. In cases when many types are possible, such as when we converted a `String` to a numeric type using `parse` in the [“Comparing the Guess to the Secret Number”](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number) section in Chapter 2, we must add a type annotation, like this: #![allow(unused)] fn main() { let guess: u32 = "42".parse().expect("Not a number!"); } If we don’t add the `: u32` type annotation shown in the preceding code, Rust will display the following error, which means the compiler needs more information from us to know which type we want to use: $ cargo build Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations) error[E0284]: type annotations needed --> src/main.rs:2:9 | 2 | let guess = "42".parse().expect("Not a number!"); | ^^^^^ ----- type must be known at this point | = note: cannot satisfy `<_ as FromStr>::Err == _` help: consider giving `guess` an explicit type | 2 | let guess: /* Type */ = "42".parse().expect("Not a number!"); | ++++++++++++ For more information about this error, try `rustc --explain E0284`. error: could not compile `no_type_annotations` (bin "no_type_annotations") due to 1 previous error You’ll see different type annotations for other data types. A _scalar_ type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. You may recognize these from other programming languages. Let’s jump into how they work in Rust. An _integer_ is a number without a fractional component. We used one integer type in Chapter 2, the `u32` type. This type declaration indicates that the value it’s associated with should be an unsigned integer (signed integer types start with `i` instead of `u`) that takes up 32 bits of space. Table 3-1 shows the built-in integer types in Rust. We can use any of these variants to declare the type of an integer value. Table 3-1: Integer Types in Rust | Length | Signed | Unsigned | | --- | --- | --- | | 8-bit | `i8` | `u8` | | 16-bit | `i16` | `u16` | | 32-bit | `i32` | `u32` | | 64-bit | `i64` | `u64` | | 128-bit | `i128` | `u128` | | Architecture-dependent | `isize` | `usize` | Each variant can be either signed or unsigned and has an explicit size. _Signed_ and _unsigned_ refer to whether it’s possible for the number to be negative—in other words, whether the number needs to have a sign with it (signed) or whether it will only ever be positive and can therefore be represented without a sign (unsigned). It’s like writing numbers on paper: When the sign matters, a number is shown with a plus sign or a minus sign; however, when it’s safe to assume the number is positive, it’s shown with no sign. Signed numbers are stored using [two’s complement](https://en.wikipedia.org/wiki/Two%27s_complement) representation. Each signed variant can store numbers from −(2n − 1) to 2n − 1 − 1 inclusive, where _n_ is the number of bits that variant uses. So, an `i8` can store numbers from −(27) to 27 − 1, which equals −128 to 127. Unsigned variants can store numbers from 0 to 2n − 1, so a `u8` can store numbers from 0 to 28 − 1, which equals 0 to 255. Additionally, the `isize` and `usize` types depend on the architecture of the computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture. You can write integer literals in any of the forms shown in Table 3-2. Note that number literals that can be multiple numeric types allow a type suffix, such as `57u8`, to designate the type. Number literals can also use `_` as a visual separator to make the number easier to read, such as `1_000`, which will have the same value as if you had specified `1000`. Table 3-2: Integer Literals in Rust | Number literals | Example | | --- | --- | | Decimal | `98_222` | | Hex | `0xff` | | Octal | `0o77` | | Binary | `0b1111_0000` | | Byte (`u8` only) | `b'A'` | So how do you know which type of integer to use? If you’re unsure, Rust’s defaults are generally good places to start: Integer types default to `i32`. The primary situation in which you’d use `isize` or `usize` is when indexing some sort of collection. Let’s say you have a variable of type `u8` that can hold values between 0 and 255. If you try to change the variable to a value outside that range, such as 256, _integer overflow_ will occur, which can result in one of two behaviors. When you’re compiling in debug mode, Rust includes checks for integer overflow that cause your program to _panic_ at runtime if this behavior occurs. Rust uses the term _panicking_ when a program exits with an error; we’ll discuss panics in more depth in the [“Unrecoverable Errors with `panic!`”](https://doc.rust-lang.org/stable/book/ch09-01-unrecoverable-errors-with-panic.html) section in Chapter 9. When you’re compiling in release mode with the `--release` flag, Rust does _not_ include checks for integer overflow that cause panics. Instead, if overflow occurs, Rust performs _two’s complement wrapping_. In short, values greater than the maximum value the type can hold “wrap around” to the minimum of the values the type can hold. In the case of a `u8`, the value 256 becomes 0, the value 257 becomes 1, and so on. The program won’t panic, but the variable will have a value that probably isn’t what you were expecting it to have. Relying on integer overflow’s wrapping behavior is considered an error. To explicitly handle the possibility of overflow, you can use these families of methods provided by the standard library for primitive numeric types: * Wrap in all modes with the `wrapping_*` methods, such as `wrapping_add`. * Return the `None` value if there is overflow with the `checked_*` methods. * Return the value and a Boolean indicating whether there was overflow with the `overflowing_*` methods. * Saturate at the value’s minimum or maximum values with the `saturating_*` methods. Rust also has two primitive types for _floating-point numbers_, which are numbers with decimal points. Rust’s floating-point types are `f32` and `f64`, which are 32 bits and 64 bits in size, respectively. The default type is `f64` because on modern CPUs, it’s roughly the same speed as `f32` but is capable of more precision. All floating-point types are signed. Here’s an example that shows floating-point numbers in action: Filename: src/main.rs fn main() { let x = 2.0; // f64 let y: f32 = 3.0; // f32 } Floating-point numbers are represented according to the IEEE-754 standard. Rust supports the basic mathematical operations you’d expect for all the number types: addition, subtraction, multiplication, division, and remainder. Integer division truncates toward zero to the nearest integer. The following code shows how you’d use each numeric operation in a `let` statement: Filename: src/main.rs fn main() { // addition let sum = 5 + 10; // subtraction let difference = 95.5 - 4.3; // multiplication let product = 4 * 30; // division let quotient = 56.7 / 32.2; let truncated = -5 / 3; // Results in -1 // remainder let remainder = 43 % 5; } Each expression in these statements uses a mathematical operator and evaluates to a single value, which is then bound to a variable. [Appendix B](https://doc.rust-lang.org/stable/book/appendix-02-operators.html) contains a list of all operators that Rust provides. As in most other programming languages, a Boolean type in Rust has two possible values: `true` and `false`. Booleans are one byte in size. The Boolean type in Rust is specified using `bool`. For example: Filename: src/main.rs fn main() { let t = true; let f: bool = false; // with explicit type annotation } The main way to use Boolean values is through conditionals, such as an `if` expression. We’ll cover how `if` expressions work in Rust in the [“Control Flow”](https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#control-flow) section. Rust’s `char` type is the language’s most primitive alphabetic type. Here are some examples of declaring `char` values: Filename: src/main.rs fn main() { let c = 'z'; let z: char = 'ℤ'; // with explicit type annotation let heart_eyed_cat = '😻'; } Note that we specify `char` literals with single quotation marks, as opposed to string literals, which use double quotation marks. Rust’s `char` type is 4 bytes in size and represents a Unicode scalar value, which means it can represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and Korean characters; emojis; and zero-width spaces are all valid `char` values in Rust. Unicode scalar values range from `U+0000` to `U+D7FF` and `U+E000` to `U+10FFFF` inclusive. However, a “character” isn’t really a concept in Unicode, so your human intuition for what a “character” is may not match up with what a `char` is in Rust. We’ll discuss this topic in detail in [“Storing UTF-8 Encoded Text with Strings”](https://doc.rust-lang.org/stable/book/ch08-02-strings.html#storing-utf-8-encoded-text-with-strings) in Chapter 8. _Compound types_ can group multiple values into one type. Rust has two primitive compound types: tuples and arrays. A _tuple_ is a general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: Once declared, they cannot grow or shrink in size. We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a type, and the types of the different values in the tuple don’t have to be the same. We’ve added optional type annotations in this example: Filename: src/main.rs fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); } The variable `tup` binds to the entire tuple because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this: Filename: src/main.rs fn main() { let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of y is: {y}"); } This program first creates a tuple and binds it to the variable `tup`. It then uses a pattern with `let` to take `tup` and turn it into three separate variables, `x`, `y`, and `z`. This is called _destructuring_ because it breaks the single tuple into three parts. Finally, the program prints the value of `y`, which is `6.4`. We can also access a tuple element directly by using a period (`.`) followed by the index of the value we want to access. For example: Filename: src/main.rs fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; } This program creates the tuple `x` and then accesses each element of the tuple using their respective indices. As with most programming languages, the first index in a tuple is 0. The tuple without any values has a special name, _unit_. This value and its corresponding type are both written `()` and represent an empty value or an empty return type. Expressions implicitly return the unit value if they don’t return any other value. Another way to have a collection of multiple values is with an _array_. Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length. We write the values in an array as a comma-separated list inside square brackets: Filename: src/main.rs fn main() { let a = [1, 2, 3, 4, 5]; } Arrays are useful when you want your data allocated on the stack, the same as the other types we have seen so far, rather than the heap (we will discuss the stack and the heap more in [Chapter 4](https://doc.rust-lang.org/stable/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap) ) or when you want to ensure that you always have a fixed number of elements. An array isn’t as flexible as the vector type, though. A vector is a similar collection type provided by the standard library that _is_ allowed to grow or shrink in size because its contents live on the heap. If you’re unsure whether to use an array or a vector, chances are you should use a vector. [Chapter 8](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html) discusses vectors in more detail. However, arrays are more useful when you know the number of elements will not need to change. For example, if you were using the names of the month in a program, you would probably use an array rather than a vector because you know it will always contain 12 elements: #![allow(unused)] fn main() { let months = ["January", "February", "March", "April", "May", "June", "July",\ "August", "September", "October", "November", "December"]; } You write an array’s type using square brackets with the type of each element, a semicolon, and then the number of elements in the array, like so: #![allow(unused)] fn main() { let a: [i32; 5] = [1, 2, 3, 4, 5]; } Here, `i32` is the type of each element. After the semicolon, the number `5` indicates the array contains five elements. You can also initialize an array to contain the same value for each element by specifying the initial value, followed by a semicolon, and then the length of the array in square brackets, as shown here: #![allow(unused)] fn main() { let a = [3; 5]; } The array named `a` will contain `5` elements that will all be set to the value `3` initially. This is the same as writing `let a = [3, 3, 3, 3, 3];` but in a more concise way. An array is a single chunk of memory of a known, fixed size that can be allocated on the stack. You can access elements of an array using indexing, like this: Filename: src/main.rs fn main() { let a = [1, 2, 3, 4, 5]; let first = a[0]; let second = a[1]; } In this example, the variable named `first` will get the value `1` because that is the value at index `[0]` in the array. The variable named `second` will get the value `2` from index `[1]` in the array. Let’s see what happens if you try to access an element of an array that is past the end of the array. Say you run this code, similar to the guessing game in Chapter 2, to get an array index from the user: Filename: src/main.rs use std::io; fn main() { let a = [1, 2, 3, 4, 5]; println!("Please enter an array index."); let mut index = String::new(); io::stdin() .read_line(&mut index) .expect("Failed to read line"); let index: usize = index .trim() .parse() .expect("Index entered was not a number"); let element = a[index]; println!("The value of the element at index {index} is: {element}"); } This code compiles successfully. If you run this code using `cargo run` and enter `0`, `1`, `2`, `3`, or `4`, the program will print out the corresponding value at that index in the array. If you instead enter a number past the end of the array, such as `10`, you’ll see output like this: thread 'main' panicked at src/main.rs:19:19: index out of bounds: the len is 5 but the index is 10 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace The program resulted in a runtime error at the point of using an invalid value in the indexing operation. The program exited with an error message and didn’t execute the final `println!` statement. When you attempt to access an element using indexing, Rust will check that the index you’ve specified is less than the array length. If the index is greater than or equal to the length, Rust will panic. This check has to happen at runtime, especially in this case, because the compiler can’t possibly know what value a user will enter when they run the code later. This is an example of Rust’s memory safety principles in action. In many low-level languages, this kind of check is not done, and when you provide an incorrect index, invalid memory can be accessed. Rust protects you against this kind of error by immediately exiting instead of allowing the memory access and continuing. Chapter 9 discusses more of Rust’s error handling and how you can write readable, safe code that neither panics nor allows invalid memory access. --- # alloc - Rust [Crate alloc](https://doc.rust-lang.org/stable/alloc/index.html#) ------------------------------------------------------------------ Crate alloc Copy item path ========================== 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#1-239) Expand description [§](https://doc.rust-lang.org/stable/alloc/index.html#the-rust-core-allocation-and-collections-library) The Rust core allocation and collections library -------------------------------------------------------------------------------------------------------------------------------------------------------- This library provides smart pointers and collections for managing heap-allocated values. This library, like core, normally doesn’t need to be used directly since its contents are re-exported in the [`std` crate](https://doc.rust-lang.org/stable/std/index.html) . Crates that use the `#![no_std]` attribute however will typically not depend on `std`, so they’d use this crate instead. ### [§](https://doc.rust-lang.org/stable/alloc/index.html#boxed-values) Boxed values The [`Box`](https://doc.rust-lang.org/stable/alloc/boxed/index.html "mod alloc::boxed") type is a smart pointer type. There can only be one owner of a [`Box`](https://doc.rust-lang.org/stable/alloc/boxed/index.html "mod alloc::boxed") , and the owner can decide to mutate the contents, which live on the heap. This type can be sent among threads efficiently as the size of a `Box` value is the same as that of a pointer. Tree-like data structures are often built with boxes because each node often has only one owner, the parent. ### [§](https://doc.rust-lang.org/stable/alloc/index.html#reference-counted-pointers) Reference counted pointers The [`Rc`](https://doc.rust-lang.org/stable/alloc/rc/index.html "mod alloc::rc") type is a non-threadsafe reference-counted pointer type intended for sharing memory within a thread. An [`Rc`](https://doc.rust-lang.org/stable/alloc/rc/index.html "mod alloc::rc") pointer wraps a type, `T`, and only allows access to `&T`, a shared reference. This type is useful when inherited mutability (such as using [`Box`](https://doc.rust-lang.org/stable/alloc/boxed/index.html "mod alloc::boxed") ) is too constraining for an application, and is often paired with the [`Cell`](https://doc.rust-lang.org/stable/core/cell/index.html "mod core::cell") or [`RefCell`](https://doc.rust-lang.org/stable/core/cell/index.html "mod core::cell") types in order to allow mutation. ### [§](https://doc.rust-lang.org/stable/alloc/index.html#atomically-reference-counted-pointers) Atomically reference counted pointers The [`Arc`](https://doc.rust-lang.org/stable/alloc/sync/index.html "mod alloc::sync") type is the threadsafe equivalent of the [`Rc`](https://doc.rust-lang.org/stable/alloc/rc/index.html "mod alloc::rc") type. It provides all the same functionality of [`Rc`](https://doc.rust-lang.org/stable/alloc/rc/index.html "mod alloc::rc") , except it requires that the contained type `T` is shareable. Additionally, [`Arc`](https://doc.rust-lang.org/stable/alloc/sync/index.html "mod alloc::sync") is itself sendable while [`Rc`](https://doc.rust-lang.org/stable/alloc/rc/index.html "mod alloc::rc") is not. This type allows for shared access to the contained data, and is often paired with synchronization primitives such as mutexes to allow mutation of shared resources. ### [§](https://doc.rust-lang.org/stable/alloc/index.html#collections) Collections Implementations of the most common general purpose data structures are defined in this library. They are re-exported through the [standard collections library](https://doc.rust-lang.org/stable/std/collections/index.html) . ### [§](https://doc.rust-lang.org/stable/alloc/index.html#heap-interfaces) Heap interfaces The [`alloc`](https://doc.rust-lang.org/stable/alloc/alloc/index.html) module defines the low-level interface to the default global allocator. It is not compatible with the libc allocator API. Modules[§](https://doc.rust-lang.org/stable/alloc/index.html#modules) ---------------------------------------------------------------------- [alloc](https://doc.rust-lang.org/stable/alloc/alloc/index.html "mod alloc::alloc") Memory allocation APIs [borrow](https://doc.rust-lang.org/stable/alloc/borrow/index.html "mod alloc::borrow") A module for working with borrowed data. [boxed](https://doc.rust-lang.org/stable/alloc/boxed/index.html "mod alloc::boxed") The `Box` type for heap allocation. [collections](https://doc.rust-lang.org/stable/alloc/collections/index.html "mod alloc::collections") Collection types. [ffi](https://doc.rust-lang.org/stable/alloc/ffi/index.html "mod alloc::ffi") Utilities related to FFI bindings. [fmt](https://doc.rust-lang.org/stable/alloc/fmt/index.html "mod alloc::fmt") Utilities for formatting and printing `String`s. [rc](https://doc.rust-lang.org/stable/alloc/rc/index.html "mod alloc::rc") Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’. [slice](https://doc.rust-lang.org/stable/alloc/slice/index.html "mod alloc::slice") Utilities for the slice primitive type. [str](https://doc.rust-lang.org/stable/alloc/str/index.html "mod alloc::str") Utilities for the `str` primitive type. [string](https://doc.rust-lang.org/stable/alloc/string/index.html "mod alloc::string") A UTF-8–encoded, growable string. [sync](https://doc.rust-lang.org/stable/alloc/sync/index.html "mod alloc::sync") Thread-safe reference-counting pointers. [task](https://doc.rust-lang.org/stable/alloc/task/index.html "mod alloc::task") Types and Traits for working with asynchronous tasks. [vec](https://doc.rust-lang.org/stable/alloc/vec/index.html "mod alloc::vec") A contiguous growable array type with heap-allocated contents, written `Vec`. [bstr](https://doc.rust-lang.org/stable/alloc/bstr/index.html "mod alloc::bstr") Experimental The `ByteStr` and `ByteString` types and trait implementations. Macros[§](https://doc.rust-lang.org/stable/alloc/index.html#macros) -------------------------------------------------------------------- [format](https://doc.rust-lang.org/stable/alloc/macro.format.html "macro alloc::format") Creates a `String` using interpolation of runtime expressions. [vec](https://doc.rust-lang.org/stable/alloc/macro.vec.html "macro alloc::vec") Creates a [`Vec`](https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html "struct alloc::vec::Vec") containing the arguments. --- # proc_macro - Rust [Crate proc\_macro](https://doc.rust-lang.org/stable/proc_macro/index.html#) ----------------------------------------------------------------------------- Crate proc\_macro Copy item path ================================ 1.15.0 · [Source](https://doc.rust-lang.org/stable/src/proc_macro/lib.rs.html#1-1630) Expand description A support library for macro authors when defining new macros. This library, provided by the standard distribution, provides the types consumed in the interfaces of procedurally defined macro definitions such as function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and custom derive attributes`#[proc_macro_derive]`. See [the book](https://doc.rust-lang.org/stable/book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes) for more. Modules[§](https://doc.rust-lang.org/stable/proc_macro/index.html#modules) --------------------------------------------------------------------------- [token\_stream](https://doc.rust-lang.org/stable/proc_macro/token_stream/index.html "mod proc_macro::token_stream") Public implementation details for the `TokenStream` type, such as iterators. [tracked\_env](https://doc.rust-lang.org/stable/proc_macro/tracked_env/index.html "mod proc_macro::tracked_env") Experimental Tracked access to environment variables. [tracked\_path](https://doc.rust-lang.org/stable/proc_macro/tracked_path/index.html "mod proc_macro::tracked_path") Experimental Tracked access to additional files. Macros[§](https://doc.rust-lang.org/stable/proc_macro/index.html#macros) ------------------------------------------------------------------------- [quote](https://doc.rust-lang.org/stable/proc_macro/macro.quote.html "macro proc_macro::quote") Experimental `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input. For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`. Structs[§](https://doc.rust-lang.org/stable/proc_macro/index.html#structs) --------------------------------------------------------------------------- [Group](https://doc.rust-lang.org/stable/proc_macro/struct.Group.html "struct proc_macro::Group") A delimited token stream. [Ident](https://doc.rust-lang.org/stable/proc_macro/struct.Ident.html "struct proc_macro::Ident") An identifier (`ident`). [LexError](https://doc.rust-lang.org/stable/proc_macro/struct.LexError.html "struct proc_macro::LexError") Error returned from `TokenStream::from_str`. [Literal](https://doc.rust-lang.org/stable/proc_macro/struct.Literal.html "struct proc_macro::Literal") A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`), character (`'a'`), byte character (`b'a'`), an integer or floating point number with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`). Boolean literals like `true` and `false` do not belong here, they are `Ident`s. [Punct](https://doc.rust-lang.org/stable/proc_macro/struct.Punct.html "struct proc_macro::Punct") A `Punct` is a single punctuation character such as `+`, `-` or `#`. [Span](https://doc.rust-lang.org/stable/proc_macro/struct.Span.html "struct proc_macro::Span") A region of source code, along with macro expansion information. [TokenStream](https://doc.rust-lang.org/stable/proc_macro/struct.TokenStream.html "struct proc_macro::TokenStream") The main type provided by this crate, representing an abstract stream of tokens, or, more specifically, a sequence of token trees. The type provides interfaces for iterating over those token trees and, conversely, collecting a number of token trees into one stream. [Diagnostic](https://doc.rust-lang.org/stable/proc_macro/struct.Diagnostic.html "struct proc_macro::Diagnostic") Experimental A structure representing a diagnostic message and associated children messages. [ExpandError](https://doc.rust-lang.org/stable/proc_macro/struct.ExpandError.html "struct proc_macro::ExpandError") Experimental Error returned from `TokenStream::expand_expr`. Enums[§](https://doc.rust-lang.org/stable/proc_macro/index.html#enums) ----------------------------------------------------------------------- [Delimiter](https://doc.rust-lang.org/stable/proc_macro/enum.Delimiter.html "enum proc_macro::Delimiter") Describes how a sequence of token trees is delimited. [Spacing](https://doc.rust-lang.org/stable/proc_macro/enum.Spacing.html "enum proc_macro::Spacing") Indicates whether a `Punct` token can join with the following token to form a multi-character operator. [TokenTree](https://doc.rust-lang.org/stable/proc_macro/enum.TokenTree.html "enum proc_macro::TokenTree") A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`). [ConversionErrorKind](https://doc.rust-lang.org/stable/proc_macro/enum.ConversionErrorKind.html "enum proc_macro::ConversionErrorKind") Experimental Errors returned when trying to retrieve a literal unescaped value. [EscapeError](https://doc.rust-lang.org/stable/proc_macro/enum.EscapeError.html "enum proc_macro::EscapeError") Errors and warnings that can occur during string, char, and byte unescaping. [Level](https://doc.rust-lang.org/stable/proc_macro/enum.Level.html "enum proc_macro::Level") Experimental An enum representing a diagnostic level. Traits[§](https://doc.rust-lang.org/stable/proc_macro/index.html#traits) ------------------------------------------------------------------------- [MultiSpan](https://doc.rust-lang.org/stable/proc_macro/trait.MultiSpan.html "trait proc_macro::MultiSpan") Experimental Trait implemented by types that can be converted into a set of `Span`s. [ToTokens](https://doc.rust-lang.org/stable/proc_macro/trait.ToTokens.html "trait proc_macro::ToTokens") Experimental Types that can be interpolated inside a [`quote!`](https://doc.rust-lang.org/stable/proc_macro/macro.quote.html "macro proc_macro::quote") invocation. Functions[§](https://doc.rust-lang.org/stable/proc_macro/index.html#functions) ------------------------------------------------------------------------------- [is\_available](https://doc.rust-lang.org/stable/proc_macro/fn.is_available.html "fn proc_macro::is_available") Determines whether proc\_macro has been made accessible to the currently running program. [quote](https://doc.rust-lang.org/stable/proc_macro/fn.quote.html "fn proc_macro::quote") Experimental Quote a `TokenStream` into a `TokenStream`. This is the actual implementation of the `quote!()` proc macro. [quote\_span](https://doc.rust-lang.org/stable/proc_macro/fn.quote_span.html "fn proc_macro::quote_span") Experimental Quote a `Span` into a `TokenStream`. This is needed to implement a custom quoter. --- # std::cmp - Rust [Module cmp](https://doc.rust-lang.org/stable/std/cmp/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module cmp Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#292) Expand description Utilities for comparing and ordering values. This module contains various tools for comparing and ordering values. In summary: * [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") overloads the `==` and `!=` operators. In cases where `Rhs` (the right hand side’s type) is `Self`, this trait corresponds to a partial equivalence relation. * [`Eq`](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") indicates that the overloaded `==` operator corresponds to an equivalence relation. * [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") and [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") are traits that allow you to define total and partial orderings between values, respectively. Implementing them overloads the `<`, `<=`, `>`, and `>=` operators. * [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") is an enum returned by the main functions of [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") and [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , and describes an ordering of two values (less, equal, or greater). * [`Reverse`](https://doc.rust-lang.org/stable/std/cmp/struct.Reverse.html "struct std::cmp::Reverse") is a struct that allows you to easily reverse an ordering. * [`max`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max "method std::cmp::Ord::max") and [`min`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min "method std::cmp::Ord::min") are functions that build off of [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") and allow you to find the maximum or minimum of two values. For more details, see the respective documentation of each item in the list. Structs[§](https://doc.rust-lang.org/stable/std/cmp/index.html#structs) ------------------------------------------------------------------------ [Reverse](https://doc.rust-lang.org/stable/std/cmp/struct.Reverse.html "struct std::cmp::Reverse") A helper struct for reverse ordering. Enums[§](https://doc.rust-lang.org/stable/std/cmp/index.html#enums) -------------------------------------------------------------------- [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") An `Ordering` is the result of a comparison between two values. Traits[§](https://doc.rust-lang.org/stable/std/cmp/index.html#traits) ---------------------------------------------------------------------- [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") Trait for comparisons corresponding to [equivalence relations](https://en.wikipedia.org/wiki/Equivalence_relation) . [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order) . [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") Trait for comparisons using the equality operator. [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order) . Functions[§](https://doc.rust-lang.org/stable/std/cmp/index.html#functions) ---------------------------------------------------------------------------- [max](https://doc.rust-lang.org/stable/std/cmp/fn.max.html "fn std::cmp::max") Compares and returns the maximum of two values. [max\_by](https://doc.rust-lang.org/stable/std/cmp/fn.max_by.html "fn std::cmp::max_by") Returns the maximum of two values with respect to the specified comparison function. [max\_by\_key](https://doc.rust-lang.org/stable/std/cmp/fn.max_by_key.html "fn std::cmp::max_by_key") Returns the element that gives the maximum value from the specified function. [min](https://doc.rust-lang.org/stable/std/cmp/fn.min.html "fn std::cmp::min") Compares and returns the minimum of two values. [min\_by](https://doc.rust-lang.org/stable/std/cmp/fn.min_by.html "fn std::cmp::min_by") Returns the minimum of two values with respect to the specified comparison function. [min\_by\_key](https://doc.rust-lang.org/stable/std/cmp/fn.min_by_key.html "fn std::cmp::min_by_key") Returns the element that gives the minimum value from the specified function. [minmax](https://doc.rust-lang.org/stable/std/cmp/fn.minmax.html "fn std::cmp::minmax") Experimental Compares and sorts two values, returning minimum and maximum. [minmax\_by](https://doc.rust-lang.org/stable/std/cmp/fn.minmax_by.html "fn std::cmp::minmax_by") Experimental Returns minimum and maximum values with respect to the specified comparison function. [minmax\_by\_key](https://doc.rust-lang.org/stable/std/cmp/fn.minmax_by_key.html "fn std::cmp::minmax_by_key") Experimental Returns minimum and maximum values with respect to the specified key function. Derive Macros[§](https://doc.rust-lang.org/stable/std/cmp/index.html#derives) ------------------------------------------------------------------------------ [Eq](https://doc.rust-lang.org/stable/std/cmp/derive.Eq.html "derive std::cmp::Eq") Derive macro generating an impl of the trait [`Eq`](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") . [Ord](https://doc.rust-lang.org/stable/std/cmp/derive.Ord.html "derive std::cmp::Ord") Derive macro generating an impl of the trait [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") . The behavior of this macro is described in detail [here](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#derivable "trait std::cmp::Ord") . [PartialEq](https://doc.rust-lang.org/stable/std/cmp/derive.PartialEq.html "derive std::cmp::PartialEq") Derive macro generating an impl of the trait [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") . The behavior of this macro is described in detail [here](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#derivable "trait std::cmp::PartialEq") . [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/derive.PartialOrd.html "derive std::cmp::PartialOrd") Derive macro generating an impl of the trait [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") . The behavior of this macro is described in detail [here](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#derivable "trait std::cmp::PartialOrd") . --- # current in std::thread - Rust [current](https://doc.rust-lang.org/stable/std/thread/fn.current.html#) ------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) ::[thread](https://doc.rust-lang.org/stable/std/thread/index.html) Function current Copy item path =============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/current.rs.html#243-253) pub fn current() -> Thread Expand description Gets a handle to the thread that invokes it. [§](https://doc.rust-lang.org/stable/std/thread/fn.current.html#examples) Examples ---------------------------------------------------------------------------------- Getting a handle to the current thread with `thread::current()`: use std::thread; let handler = thread::Builder::new() .name("named thread".into()) .spawn(|| { let handle = thread::current(); assert_eq!(handle.name(), Some("named thread")); }) .unwrap(); handler.join().unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++%0A++++let+handler+=+thread::Builder::new()%0A++++++++.name(%22named+thread%22.into())%0A++++++++.spawn(%7C%7C+%7B%0A++++++++++++let+handle+=+thread::current();%0A++++++++++++assert_eq!(handle.name(),+Some(%22named+thread%22));%0A++++++++%7D)%0A++++++++.unwrap();%0A++++%0A++++handler.join().unwrap();%0A%7D&edition=2024 "Run code") --- # format in std - Rust [format](https://doc.rust-lang.org/stable/std/macro.format.html#) ------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro format Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/macros.rs.html#105) macro_rules! format { ($($arg:tt)*) => { ... }; } Expand description Creates a `String` using interpolation of runtime expressions. The first argument `format!` receives is a format string. This must be a string literal. The power of the formatting string is in the `{}`s contained. Additional parameters passed to `format!` replace the `{}`s within the formatting string in the order given unless named or positional parameters are used. See [the formatting syntax documentation in `std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) for details. A common use for `format!` is concatenation and interpolation of strings. The same convention is used with [`print!`](https://doc.rust-lang.org/stable/std/macro.print.html) and [`write!`](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") macros, depending on the intended destination of the string; all these macros internally use [`format_args!`](https://doc.rust-lang.org/stable/std/macro.format_args.html "macro std::format_args") . To convert a single value to a string, use the [`to_string`](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") method. This will use the [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") formatting trait. To concatenate literals into a `&'static str`, use the [`concat!`](https://doc.rust-lang.org/stable/std/macro.concat.html "macro std::concat") macro. [§](https://doc.rust-lang.org/stable/std/macro.format.html#panics) Panics ------------------------------------------------------------------------- `format!` panics if a formatting trait implementation returns an error. This indicates an incorrect implementation since `fmt::Write for String` never returns an error itself. [§](https://doc.rust-lang.org/stable/std/macro.format.html#examples) Examples ----------------------------------------------------------------------------- format!("test"); // => "test" format!("hello {}", "world!"); // => "hello world!" format!("x = {}, y = {val}", 10, val = 30); // => "x = 10, y = 30" let (x, y) = (1, 2); format!("{x} + {y} = 3"); // => "1 + 2 = 3" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++format!(%22test%22);+++++++++++++++++++++++++++++//+=%3E+%22test%22%0A++++format!(%22hello+%7B%7D%22,+%22world!%22);+++++++++++++++//+=%3E+%22hello+world!%22%0A++++format!(%22x+=+%7B%7D,+y+=+%7Bval%7D%22,+10,+val+=+30);++//+=%3E+%22x+=+10,+y+=+30%22%0A++++let+(x,+y)+=+(1,+2);%0A++++format!(%22%7Bx%7D+%2B+%7By%7D+=+3%22);%0A%7D&edition=2024 "Run code") --- # std::boxed - Rust [Module boxed](https://doc.rust-lang.org/stable/std/boxed/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module boxed Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#214) Expand description The `Box` type for heap allocation. [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") , casually referred to as a ‘box’, provides the simplest form of heap allocation in Rust. Boxes provide ownership for this allocation, and drop their contents when they go out of scope. Boxes also ensure that they never allocate more than `isize::MAX` bytes. [§](https://doc.rust-lang.org/stable/std/boxed/index.html#examples) Examples ---------------------------------------------------------------------------- Move a value from the stack to the heap by creating a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") : let val: u8 = 5; let boxed: Box = Box::new(val); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+val:+u8+=+5;%0A++++let+boxed:+Box%3Cu8%3E+=+Box::new(val);%0A%7D&edition=2024 "Run code") Move a value from a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") back to the stack by [dereferencing](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") : let boxed: Box = Box::new(5); let val: u8 = *boxed; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+boxed:+Box%3Cu8%3E+=+Box::new(5);%0A++++let+val:+u8+=+*boxed;%0A%7D&edition=2024 "Run code") Creating a recursive data structure: #[derive(Debug)] enum List { Cons(T, Box>), Nil, } let list: List = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); println!("{list:?}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(dead_code)%5D%0A++++%23%5Bderive(Debug)%5D%0A++++enum+List%3CT%3E+%7B%0A++++++++Cons(T,+Box%3CList%3CT%3E%3E),%0A++++++++Nil,%0A++++%7D%0A++++%0A++++let+list:+List%3Ci32%3E+=+List::Cons(1,+Box::new(List::Cons(2,+Box::new(List::Nil))));%0A++++println!(%22%7Blist:?%7D%22);%0A%7D&edition=2024 "Run code") This will print `Cons(1, Cons(2, Nil))`. Recursive structures must be boxed, because if the definition of `Cons` looked like this: [ⓘ](https://doc.rust-lang.org/stable/std/boxed/index.html# "This example deliberately fails to compile") Cons(T, List), [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+List%3CT%3E+%7B%0A++++Cons(T,+List%3CT%3E),%0A++++%7D%0A%7D&edition=2024 "Run code") It wouldn’t work. This is because the size of a `List` depends on how many elements are in the list, and so we don’t know how much memory to allocate for a `Cons`. By introducing a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") , which has a defined size, we know how big `Cons` needs to be. [§](https://doc.rust-lang.org/stable/std/boxed/index.html#memory-layout) Memory layout -------------------------------------------------------------------------------------- For non-zero-sized values, a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") will use the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator for its allocation. It is valid to convert both ways between a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") and a raw pointer allocated with the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator, given that the [`Layout`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") used with the allocator is correct for the type and the raw pointer points to a valid value of the right type. More precisely, a `value: *mut T` that has been allocated with the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator with `Layout::for_value(&*value)` may be converted into a box using [`Box::::from_raw(value)`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.from_raw "associated function std::boxed::Box::from_raw") . Conversely, the memory backing a `value: *mut T` obtained from [`Box::::into_raw`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.into_raw "associated function std::boxed::Box::into_raw") may be deallocated using the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator with [`Layout::for_value(&*value)`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.for_value "associated function std::alloc::Layout::for_value") . For zero-sized values, the `Box` pointer has to be non-null and sufficiently aligned. The recommended way to build a Box to a ZST if `Box::new` cannot be used is to use [`ptr::NonNull::dangling`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.dangling "associated function std::ptr::NonNull::dangling") . On top of these basic layout requirements, a `Box` must point to a valid value of `T`. So long as `T: Sized`, a `Box` is guaranteed to be represented as a single pointer and is also ABI-compatible with C pointers (i.e. the C type `T*`). This means that if you have extern “C” Rust functions that will be called from C, you can define those Rust functions using `Box` types, and use `T*` as corresponding type on the C side. As an example, consider this C header which declares functions that create and destroy some kind of `Foo` value: /* C header */ /* Returns ownership to the caller */ struct Foo* foo_new(void); /* Takes ownership from the caller; no-op when invoked with null */ void foo_delete(struct Foo*); These two functions might be implemented in Rust as follows. Here, the `struct Foo*` type from C is translated to `Box`, which captures the ownership constraints. Note also that the nullable argument to `foo_delete` is represented in Rust as `Option>`, since `Box` cannot be null. #[repr(C)] pub struct Foo; #[unsafe(no_mangle)] pub extern "C" fn foo_new() -> Box { Box::new(Foo) } #[unsafe(no_mangle)] pub extern "C" fn foo_delete(_: Option>) {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Brepr(C)%5D%0A++++pub+struct+Foo;%0A++++%0A++++%23%5Bunsafe(no_mangle)%5D%0A++++pub+extern+%22C%22+fn+foo_new()+-%3E+Box%3CFoo%3E+%7B%0A++++++++Box::new(Foo)%0A++++%7D%0A++++%0A++++%23%5Bunsafe(no_mangle)%5D%0A++++pub+extern+%22C%22+fn+foo_delete(_:+Option%3CBox%3CFoo%3E%3E)+%7B%7D%0A%7D&edition=2024 "Run code") Even though `Box` has the same representation and C ABI as a C pointer, this does not mean that you can convert an arbitrary `T*` into a `Box` and expect things to work. `Box` values will always be fully aligned, non-null pointers. Moreover, the destructor for `Box` will attempt to free the value with the global allocator. In general, the best practice is to only use `Box` for pointers that originated from the global allocator. **Important.** At least at present, you should avoid using `Box` types for functions that are defined in C but invoked from Rust. In those cases, you should directly mirror the C types as closely as possible. Using types like `Box` where the C definition is just using `T*` can lead to undefined behavior, as described in [rust-lang/unsafe-code-guidelines#198](https://github.com/rust-lang/unsafe-code-guidelines/issues/198) . [§](https://doc.rust-lang.org/stable/std/boxed/index.html#considerations-for-unsafe-code) Considerations for unsafe code ------------------------------------------------------------------------------------------------------------------------ **Warning: This section is not normative and is subject to change, possibly being relaxed in the future! It is a simplified summary of the rules currently implemented in the compiler.** The aliasing rules for `Box` are the same as for `&mut T`. `Box` asserts uniqueness over its content. Using raw pointers derived from a box after that box has been mutated through, moved or borrowed as `&mut T` is not allowed. For more guidance on working with box from unsafe code, see [rust-lang/unsafe-code-guidelines#326](https://github.com/rust-lang/unsafe-code-guidelines/issues/326) . [§](https://doc.rust-lang.org/stable/std/boxed/index.html#editions) Editions ---------------------------------------------------------------------------- A special case exists for the implementation of `IntoIterator` for arrays on the Rust 2021 edition, as documented [here](https://doc.rust-lang.org/stable/std/primitive.array.html "primitive array") . Unfortunately, it was later found that a similar workaround should be added for boxed slices, and this was applied in the 2024 edition. Specifically, `IntoIterator` is implemented for `Box<[T]>` on all editions, but specific calls to `into_iter()` for boxed slices will defer to the slice implementation on editions before 2024: [ⓘ](https://doc.rust-lang.org/stable/std/boxed/index.html# "This example runs with edition 2021") // Rust 2015, 2018, and 2021: let boxed_slice: Box<[i32]> = vec![0; 3].into_boxed_slice(); // This creates a slice iterator, producing references to each value. for item in boxed_slice.into_iter().enumerate() { let (i, x): (usize, &i32) = item; println!("boxed_slice[{i}] = {x}"); } // The `boxed_slice_into_iter` lint suggests this change for future compatibility: for item in boxed_slice.iter().enumerate() { let (i, x): (usize, &i32) = item; println!("boxed_slice[{i}] = {x}"); } // You can explicitly iterate a boxed slice by value using `IntoIterator::into_iter` for item in IntoIterator::into_iter(boxed_slice).enumerate() { let (i, x): (usize, i32) = item; println!("boxed_slice[{i}] = {x}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A//+Rust+2015,+2018,+and+2021:%0A%0A%23!%5Ballow(boxed_slice_into_iter)%5D%0A+//+override+our+%60deny(warnings)%60%0Afn+main()+%7B%0A++++let+boxed_slice:+Box%3C%5Bi32%5D%3E+=+vec!%5B0;+3%5D.into_boxed_slice();%0A++++%0A++++//+This+creates+a+slice+iterator,+producing+references+to+each+value.%0A++++for+item+in+boxed_slice.into_iter().enumerate()+%7B%0A++++++++let+(i,+x):+(usize,+%26i32)+=+item;%0A++++++++println!(%22boxed_slice%5B%7Bi%7D%5D+=+%7Bx%7D%22);%0A++++%7D%0A++++%0A++++//+The+%60boxed_slice_into_iter%60+lint+suggests+this+change+for+future+compatibility:%0A++++for+item+in+boxed_slice.iter().enumerate()+%7B%0A++++++++let+(i,+x):+(usize,+%26i32)+=+item;%0A++++++++println!(%22boxed_slice%5B%7Bi%7D%5D+=+%7Bx%7D%22);%0A++++%7D%0A++++%0A++++//+You+can+explicitly+iterate+a+boxed+slice+by+value+using+%60IntoIterator::into_iter%60%0A++++for+item+in+IntoIterator::into_iter(boxed_slice).enumerate()+%7B%0A++++++++let+(i,+x):+(usize,+i32)+=+item;%0A++++++++println!(%22boxed_slice%5B%7Bi%7D%5D+=+%7Bx%7D%22);%0A++++%7D%0A%7D&edition=2021 "Run code") Similar to the array implementation, this may be modified in the future to remove this override, and it’s best to avoid relying on this edition-dependent behavior if you wish to preserve compatibility with future versions of the compiler. Structs[§](https://doc.rust-lang.org/stable/std/boxed/index.html#structs) -------------------------------------------------------------------------- [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") A pointer type that uniquely owns a heap allocation of type `T`. [ThinBox](https://doc.rust-lang.org/stable/std/boxed/struct.ThinBox.html "struct std::boxed::ThinBox") Experimental ThinBox. --- # std::char - Rust [Module char](https://doc.rust-lang.org/stable/std/char/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module char Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#310) Expand description Utilities for the `char` primitive type. _[See also the `char` primitive type](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") ._ The `char` type represents a single character. More specifically, since ‘character’ isn’t a well-defined concept in Unicode, `char` is a ‘[Unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value) ’, which is similar to, but not the same as, a ‘[Unicode code point](https://www.unicode.org/glossary/#code_point) ’. This module exists for technical reasons, the primary documentation for `char` is directly on [the `char` primitive type](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") itself. This module is the home of the iterator implementations for the iterators implemented on `char`, as well as some useful constants and conversion functions that convert various types to `char`. Structs[§](https://doc.rust-lang.org/stable/std/char/index.html#structs) ------------------------------------------------------------------------- [CharTryFromError](https://doc.rust-lang.org/stable/std/char/struct.CharTryFromError.html "struct std::char::CharTryFromError") The error type returned when a conversion from [`u32`](https://doc.rust-lang.org/stable/std/primitive.u32.html "primitive u32") to [`char`](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") fails. [DecodeUtf16](https://doc.rust-lang.org/stable/std/char/struct.DecodeUtf16.html "struct std::char::DecodeUtf16") An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s. [DecodeUtf16Error](https://doc.rust-lang.org/stable/std/char/struct.DecodeUtf16Error.html "struct std::char::DecodeUtf16Error") An error that can be returned when decoding UTF-16 code points. [EscapeDebug](https://doc.rust-lang.org/stable/std/char/struct.EscapeDebug.html "struct std::char::EscapeDebug") An iterator that yields the literal escape code of a `char`. [EscapeDefault](https://doc.rust-lang.org/stable/std/char/struct.EscapeDefault.html "struct std::char::EscapeDefault") An iterator that yields the literal escape code of a `char`. [EscapeUnicode](https://doc.rust-lang.org/stable/std/char/struct.EscapeUnicode.html "struct std::char::EscapeUnicode") Returns an iterator that yields the hexadecimal Unicode escape of a character, as `char`s. [ParseCharError](https://doc.rust-lang.org/stable/std/char/struct.ParseCharError.html "struct std::char::ParseCharError") An error which can be returned when parsing a char. [ToLowercase](https://doc.rust-lang.org/stable/std/char/struct.ToLowercase.html "struct std::char::ToLowercase") Returns an iterator that yields the lowercase equivalent of a `char`. [ToUppercase](https://doc.rust-lang.org/stable/std/char/struct.ToUppercase.html "struct std::char::ToUppercase") Returns an iterator that yields the uppercase equivalent of a `char`. [TryFromCharError](https://doc.rust-lang.org/stable/std/char/struct.TryFromCharError.html "struct std::char::TryFromCharError") The error type returned when a checked char conversion fails. Constants[§](https://doc.rust-lang.org/stable/std/char/index.html#constants) ----------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/char/constant.MAX.html "constant std::char::MAX") The highest valid code point a `char` can have, `'\u{10FFFF}'`. Use [`char::MAX`](https://doc.rust-lang.org/stable/std/primitive.char.html#associatedconstant.MAX "associated constant char::MAX") instead. [REPLACEMENT\_CHARACTER](https://doc.rust-lang.org/stable/std/char/constant.REPLACEMENT_CHARACTER.html "constant std::char::REPLACEMENT_CHARACTER") `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a decoding error. Use [`char::REPLACEMENT_CHARACTER`](https://doc.rust-lang.org/stable/std/primitive.char.html#associatedconstant.REPLACEMENT_CHARACTER "associated constant char::REPLACEMENT_CHARACTER") instead. [UNICODE\_VERSION](https://doc.rust-lang.org/stable/std/char/constant.UNICODE_VERSION.html "constant std::char::UNICODE_VERSION") The version of [Unicode](https://www.unicode.org/) that the Unicode parts of `char` and `str` methods are based on. Use [`char::UNICODE_VERSION`](https://doc.rust-lang.org/stable/std/primitive.char.html#associatedconstant.UNICODE_VERSION "associated constant char::UNICODE_VERSION") instead. [MAX\_LEN\_UTF8](https://doc.rust-lang.org/stable/std/char/constant.MAX_LEN_UTF8.html "constant std::char::MAX_LEN_UTF8") Experimental The maximum number of bytes required to [encode](https://doc.rust-lang.org/stable/std/primitive.char.html#method.encode_utf8 "method char::encode_utf8") a `char` to UTF-8 encoding. [MAX\_LEN\_UTF16](https://doc.rust-lang.org/stable/std/char/constant.MAX_LEN_UTF16.html "constant std::char::MAX_LEN_UTF16") Experimental The maximum number of two-byte units required to [encode](https://doc.rust-lang.org/stable/std/primitive.char.html#method.encode_utf16 "method char::encode_utf16") a `char` to UTF-16 encoding. Functions[§](https://doc.rust-lang.org/stable/std/char/index.html#functions) ----------------------------------------------------------------------------- [decode\_utf16](https://doc.rust-lang.org/stable/std/char/fn.decode_utf16.html "fn std::char::decode_utf16") Creates an iterator over the UTF-16 encoded code points in `iter`, returning unpaired surrogates as `Err`s. Use [`char::decode_utf16`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.decode_utf16 "associated function char::decode_utf16") instead. [from\_digit](https://doc.rust-lang.org/stable/std/char/fn.from_digit.html "fn std::char::from_digit") Converts a digit in the given radix to a `char`. Use [`char::from_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_digit "associated function char::from_digit") instead. [from\_u32](https://doc.rust-lang.org/stable/std/char/fn.from_u32.html "fn std::char::from_u32") Converts a `u32` to a `char`. Use [`char::from_u32`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_u32 "associated function char::from_u32") instead. [from\_u32\_unchecked](https://doc.rust-lang.org/stable/std/char/fn.from_u32_unchecked.html "fn std::char::from_u32_unchecked") ⚠ Converts a `u32` to a `char`, ignoring validity. Use [`char::from_u32_unchecked`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.from_u32_unchecked "associated function char::from_u32_unchecked") instead. --- # test - Rust [Crate test](https://doc.rust-lang.org/stable/test/index.html#) ---------------------------------------------------------------- Crate test Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/test/lib.rs.html#1-795) 🔬This is a nightly-only experimental API. (`test`) Expand description Support code for rustc’s built in unit-test and micro-benchmarking framework. Almost all user code will only be interested in `Bencher` and `black_box`. All other interactions (such as writing tests and benchmarks themselves) should be done via the `#[test]` and `#[bench]` attributes. See the [Testing Chapter](https://doc.rust-lang.org/stable/book/ch11-00-testing.html) of the book for more details. Re-exports[§](https://doc.rust-lang.org/stable/test/index.html#reexports) -------------------------------------------------------------------------- `pub use self::bench::[Bencher](https://doc.rust-lang.org/stable/test/bench/struct.Bencher.html "struct test::bench::Bencher") ;`Experimental `pub use self::bench::[black_box](https://doc.rust-lang.org/stable/test/bench/fn.black_box.html "fn test::bench::black_box") ;`Experimental `pub use self::[ColorConfig](https://doc.rust-lang.org/stable/test/enum.ColorConfig.html "enum test::ColorConfig") ::*;`Experimental `pub use self::types::[TestName](https://doc.rust-lang.org/stable/test/enum.TestName.html "enum test::TestName") ::*;`Experimental `pub use [NamePadding](https://doc.rust-lang.org/stable/test/enum.NamePadding.html "enum test::NamePadding") ::*;`Experimental `pub use [TestFn](https://doc.rust-lang.org/stable/test/enum.TestFn.html "enum test::TestFn") ::*;`Experimental `pub use [TestName](https://doc.rust-lang.org/stable/test/enum.TestName.html "enum test::TestName") ::*;`Experimental Modules[§](https://doc.rust-lang.org/stable/test/index.html#modules) --------------------------------------------------------------------- [bench](https://doc.rust-lang.org/stable/test/bench/index.html "mod test::bench") Experimental Benchmarking module. [stats](https://doc.rust-lang.org/stable/test/stats/index.html "mod test::stats") Experimental [test](https://doc.rust-lang.org/stable/test/test/index.html "mod test::test") Experimental Structs[§](https://doc.rust-lang.org/stable/test/index.html#structs) --------------------------------------------------------------------- [Options](https://doc.rust-lang.org/stable/test/struct.Options.html "struct test::Options") Experimental Options for the test run defined by the caller (instead of CLI arguments). In case we want to add other options as well, just add them in this struct. [TestDesc](https://doc.rust-lang.org/stable/test/struct.TestDesc.html "struct test::TestDesc") Experimental [TestDescAndFn](https://doc.rust-lang.org/stable/test/struct.TestDescAndFn.html "struct test::TestDescAndFn") Experimental [TestId](https://doc.rust-lang.org/stable/test/struct.TestId.html "struct test::TestId") Experimental [TestOpts](https://doc.rust-lang.org/stable/test/struct.TestOpts.html "struct test::TestOpts") Experimental Enums[§](https://doc.rust-lang.org/stable/test/index.html#enums) ----------------------------------------------------------------- [ColorConfig](https://doc.rust-lang.org/stable/test/enum.ColorConfig.html "enum test::ColorConfig") Experimental Whether should console output be colored or not [NamePadding](https://doc.rust-lang.org/stable/test/enum.NamePadding.html "enum test::NamePadding") Experimental [OutputFormat](https://doc.rust-lang.org/stable/test/enum.OutputFormat.html "enum test::OutputFormat") Experimental Format of the test results output [RunIgnored](https://doc.rust-lang.org/stable/test/enum.RunIgnored.html "enum test::RunIgnored") Experimental Whether ignored test should be run or not [ShouldPanic](https://doc.rust-lang.org/stable/test/enum.ShouldPanic.html "enum test::ShouldPanic") Experimental Whether test is expected to panic or not [TestFn](https://doc.rust-lang.org/stable/test/enum.TestFn.html "enum test::TestFn") Experimental [TestName](https://doc.rust-lang.org/stable/test/enum.TestName.html "enum test::TestName") Experimental [TestType](https://doc.rust-lang.org/stable/test/enum.TestType.html "enum test::TestType") Experimental Type of the test according to the [Rust book](https://doc.rust-lang.org/cargo/guide/tests.html) conventions. Constants[§](https://doc.rust-lang.org/stable/test/index.html#constants) ------------------------------------------------------------------------- [ERROR\_EXIT\_CODE](https://doc.rust-lang.org/stable/test/constant.ERROR_EXIT_CODE.html "constant test::ERROR_EXIT_CODE") Experimental Process exit code to be used to indicate test failures. Functions[§](https://doc.rust-lang.org/stable/test/index.html#functions) ------------------------------------------------------------------------- [assert\_test\_result](https://doc.rust-lang.org/stable/test/fn.assert_test_result.html "fn test::assert_test_result") Experimental Invoked when unit tests terminate. Returns `Result::Err` if the test is considered a failure. By default, invokes `report()` and checks for a `0` result. [convert\_benchmarks\_to\_tests](https://doc.rust-lang.org/stable/test/fn.convert_benchmarks_to_tests.html "fn test::convert_benchmarks_to_tests") Experimental [filter\_tests](https://doc.rust-lang.org/stable/test/fn.filter_tests.html "fn test::filter_tests") Experimental [print\_merged\_doctests\_times](https://doc.rust-lang.org/stable/test/fn.print_merged_doctests_times.html "fn test::print_merged_doctests_times") Experimental Public API used by rustdoc to display the `total` and `compilation` times in the expected format. [run\_test](https://doc.rust-lang.org/stable/test/fn.run_test.html "fn test::run_test") Experimental [run\_tests](https://doc.rust-lang.org/stable/test/fn.run_tests.html "fn test::run_tests") Experimental [run\_tests\_console](https://doc.rust-lang.org/stable/test/fn.run_tests_console.html "fn test::run_tests_console") Experimental A simple console test runner. Runs provided tests reporting process and results to the stdout. [test\_main](https://doc.rust-lang.org/stable/test/fn.test_main.html "fn test::test_main") Experimental [test\_main\_static](https://doc.rust-lang.org/stable/test/fn.test_main_static.html "fn test::test_main_static") Experimental A variant optimized for invocation with a static test vector. This will panic (intentionally) when fed any dynamic tests. [test\_main\_static\_abort](https://doc.rust-lang.org/stable/test/fn.test_main_static_abort.html "fn test::test_main_static_abort") Experimental A variant optimized for invocation with a static test vector. This will panic (intentionally) when fed any dynamic tests. [test\_main\_with\_exit\_callback](https://doc.rust-lang.org/stable/test/fn.test_main_with_exit_callback.html "fn test::test_main_with_exit_callback") Experimental --- # std::env - Rust [Module env](https://doc.rust-lang.org/stable/std/env/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module env Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#1-1164) Expand description Inspection and manipulation of the process’s environment. This module contains functions to inspect various aspects such as environment variables, process arguments, the current directory, and various other important directories. There are several functions and structs in this module that have a counterpart ending in `os`. Those ending in `os` will return an [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") and those without will return a [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") . Modules[§](https://doc.rust-lang.org/stable/std/env/index.html#modules) ------------------------------------------------------------------------ [consts](https://doc.rust-lang.org/stable/std/env/consts/index.html "mod std::env::consts") Constants associated with the current target Structs[§](https://doc.rust-lang.org/stable/std/env/index.html#structs) ------------------------------------------------------------------------ [Args](https://doc.rust-lang.org/stable/std/env/struct.Args.html "struct std::env::Args") An iterator over the arguments of a process, yielding a [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") value for each argument. [ArgsOs](https://doc.rust-lang.org/stable/std/env/struct.ArgsOs.html "struct std::env::ArgsOs") An iterator over the arguments of a process, yielding an [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") value for each argument. [JoinPathsError](https://doc.rust-lang.org/stable/std/env/struct.JoinPathsError.html "struct std::env::JoinPathsError") The error type for operations on the `PATH` variable. Possibly returned from [`env::join_paths()`](https://doc.rust-lang.org/stable/std/env/fn.join_paths.html "fn std::env::join_paths") . [SplitPaths](https://doc.rust-lang.org/stable/std/env/struct.SplitPaths.html "struct std::env::SplitPaths") An iterator that splits an environment variable into paths according to platform-specific conventions. [Vars](https://doc.rust-lang.org/stable/std/env/struct.Vars.html "struct std::env::Vars") An iterator over a snapshot of the environment variables of this process. [VarsOs](https://doc.rust-lang.org/stable/std/env/struct.VarsOs.html "struct std::env::VarsOs") An iterator over a snapshot of the environment variables of this process. Enums[§](https://doc.rust-lang.org/stable/std/env/index.html#enums) -------------------------------------------------------------------- [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") The error type for operations interacting with environment variables. Possibly returned from [`env::var()`](https://doc.rust-lang.org/stable/std/env/fn.var.html "fn std::env::var") . Functions[§](https://doc.rust-lang.org/stable/std/env/index.html#functions) ---------------------------------------------------------------------------- [args](https://doc.rust-lang.org/stable/std/env/fn.args.html "fn std::env::args") Returns the arguments that this program was started with (normally passed via the command line). [args\_os](https://doc.rust-lang.org/stable/std/env/fn.args_os.html "fn std::env::args_os") Returns the arguments that this program was started with (normally passed via the command line). [current\_dir](https://doc.rust-lang.org/stable/std/env/fn.current_dir.html "fn std::env::current_dir") Returns the current working directory as a [`PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") . [current\_exe](https://doc.rust-lang.org/stable/std/env/fn.current_exe.html "fn std::env::current_exe") Returns the full filesystem path of the current running executable. [home\_dir](https://doc.rust-lang.org/stable/std/env/fn.home_dir.html "fn std::env::home_dir") Returns the path of the current user’s home directory if known. [join\_paths](https://doc.rust-lang.org/stable/std/env/fn.join_paths.html "fn std::env::join_paths") Joins a collection of [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") s appropriately for the `PATH` environment variable. [remove\_var](https://doc.rust-lang.org/stable/std/env/fn.remove_var.html "fn std::env::remove_var") ⚠ Removes an environment variable from the environment of the currently running process. [set\_current\_dir](https://doc.rust-lang.org/stable/std/env/fn.set_current_dir.html "fn std::env::set_current_dir") Changes the current working directory to the specified path. [set\_var](https://doc.rust-lang.org/stable/std/env/fn.set_var.html "fn std::env::set_var") ⚠ Sets the environment variable `key` to the value `value` for the currently running process. [split\_paths](https://doc.rust-lang.org/stable/std/env/fn.split_paths.html "fn std::env::split_paths") Parses input according to platform conventions for the `PATH` environment variable. [temp\_dir](https://doc.rust-lang.org/stable/std/env/fn.temp_dir.html "fn std::env::temp_dir") Returns the path of a temporary directory. [var](https://doc.rust-lang.org/stable/std/env/fn.var.html "fn std::env::var") Fetches the environment variable `key` from the current process. [var\_os](https://doc.rust-lang.org/stable/std/env/fn.var_os.html "fn std::env::var_os") Fetches the environment variable `key` from the current process, returning [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if the variable isn’t set or if there is another error. [vars](https://doc.rust-lang.org/stable/std/env/fn.vars.html "fn std::env::vars") Returns an iterator of (variable, value) pairs of strings, for all the environment variables of the current process. [vars\_os](https://doc.rust-lang.org/stable/std/env/fn.vars_os.html "fn std::env::vars_os") Returns an iterator of (variable, value) pairs of OS strings, for all the environment variables of the current process. --- # std::default - Rust [Module default](https://doc.rust-lang.org/stable/std/default/index.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module default Copy item path ============================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#294) Expand description The `Default` trait for types with a default value. Traits[§](https://doc.rust-lang.org/stable/std/default/index.html#traits) -------------------------------------------------------------------------- [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") A trait for giving a type a useful default value. Derive Macros[§](https://doc.rust-lang.org/stable/std/default/index.html#derives) ---------------------------------------------------------------------------------- [Default](https://doc.rust-lang.org/stable/std/default/derive.Default.html "derive std::default::Default") Derive macro generating an impl of the trait `Default`. --- # std::result - Rust [Module result](https://doc.rust-lang.org/stable/std/result/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module result Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#327) Expand description Error handling with the `Result` type. [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is the type used for returning and propagating errors. It is an enum with the variants, [`Ok(T)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") , representing success and containing a value, and [`Err(E)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") , representing error and containing an error value. enum Result { Ok(T), Err(E), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(dead_code)%5D%0A++++enum+Result%3CT,+E%3E+%7B%0A+++++++Ok(T),%0A+++++++Err(E),%0A++++%7D%0A%7D&edition=2024 "Run code") Functions return [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") whenever errors are expected and recoverable. In the `std` crate, [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is most prominently used for [I/O](https://doc.rust-lang.org/stable/std/io/index.html) . A simple function returning [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") might be defined and used like so: #[derive(Debug)] enum Version { Version1, Version2 } fn parse_version(header: &[u8]) -> Result { match header.get(0) { None => Err("invalid header length"), Some(&1) => Ok(Version::Version1), Some(&2) => Ok(Version::Version2), Some(_) => Err("invalid version"), } } let version = parse_version(&[1, 2, 3, 4]); match version { Ok(v) => println!("working with version: {v:?}"), Err(e) => println!("error parsing header: {e:?}"), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(Debug)%5D%0A++++enum+Version+%7B+Version1,+Version2+%7D%0A++++%0A++++fn+parse_version(header:+%26%5Bu8%5D)+-%3E+Result%3CVersion,+%26%27static+str%3E+%7B%0A++++++++match+header.get(0)+%7B%0A++++++++++++None+=%3E+Err(%22invalid+header+length%22),%0A++++++++++++Some(%261)+=%3E+Ok(Version::Version1),%0A++++++++++++Some(%262)+=%3E+Ok(Version::Version2),%0A++++++++++++Some(_)+=%3E+Err(%22invalid+version%22),%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+version+=+parse_version(%26%5B1,+2,+3,+4%5D);%0A++++match+version+%7B%0A++++++++Ok(v)+=%3E+println!(%22working+with+version:+%7Bv:?%7D%22),%0A++++++++Err(e)+=%3E+println!(%22error+parsing+header:+%7Be:?%7D%22),%0A++++%7D%0A%7D&edition=2024 "Run code") Pattern matching on [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") s is clear and straightforward for simple cases, but [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") comes with some convenience methods that make working with it more succinct. // The `is_ok` and `is_err` methods do what they say. let good_result: Result = Ok(10); let bad_result: Result = Err(10); assert!(good_result.is_ok() && !good_result.is_err()); assert!(bad_result.is_err() && !bad_result.is_ok()); // `map` and `map_err` consume the `Result` and produce another. let good_result: Result = good_result.map(|i| i + 1); let bad_result: Result = bad_result.map_err(|i| i - 1); assert_eq!(good_result, Ok(11)); assert_eq!(bad_result, Err(9)); // Use `and_then` to continue the computation. let good_result: Result = good_result.and_then(|i| Ok(i == 11)); assert_eq!(good_result, Ok(true)); // Use `or_else` to handle the error. let bad_result: Result = bad_result.or_else(|i| Ok(i + 20)); assert_eq!(bad_result, Ok(29)); // Consume the result and return the contents with `unwrap`. let final_awesome_result = good_result.unwrap(); assert!(final_awesome_result) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+The+%60is_ok%60+and+%60is_err%60+methods+do+what+they+say.%0A++++let+good_result:+Result%3Ci32,+i32%3E+=+Ok(10);%0A++++let+bad_result:+Result%3Ci32,+i32%3E+=+Err(10);%0A++++assert!(good_result.is_ok()+%26%26+!good_result.is_err());%0A++++assert!(bad_result.is_err()+%26%26+!bad_result.is_ok());%0A++++%0A++++//+%60map%60+and+%60map_err%60+consume+the+%60Result%60+and+produce+another.%0A++++let+good_result:+Result%3Ci32,+i32%3E+=+good_result.map(%7Ci%7C+i+%2B+1);%0A++++let+bad_result:+Result%3Ci32,+i32%3E+=+bad_result.map_err(%7Ci%7C+i+-+1);%0A++++assert_eq!(good_result,+Ok(11));%0A++++assert_eq!(bad_result,+Err(9));%0A++++%0A++++//+Use+%60and_then%60+to+continue+the+computation.%0A++++let+good_result:+Result%3Cbool,+i32%3E+=+good_result.and_then(%7Ci%7C+Ok(i+==+11));%0A++++assert_eq!(good_result,+Ok(true));%0A++++%0A++++//+Use+%60or_else%60+to+handle+the+error.%0A++++let+bad_result:+Result%3Ci32,+i32%3E+=+bad_result.or_else(%7Ci%7C+Ok(i+%2B+20));%0A++++assert_eq!(bad_result,+Ok(29));%0A++++%0A++++//+Consume+the+result+and+return+the+contents+with+%60unwrap%60.%0A++++let+final_awesome_result+=+good_result.unwrap();%0A++++assert!(final_awesome_result)%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/result/index.html#results-must-be-used) Results must be used ----------------------------------------------------------------------------------------------------- A common problem with using return values to indicate errors is that it is easy to ignore the return value, thus failing to handle the error. [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is annotated with the `#[must_use]` attribute, which will cause the compiler to issue a warning when a Result value is ignored. This makes [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") especially useful with functions that may encounter errors but don’t otherwise return a useful value. Consider the [`write_all`](https://doc.rust-lang.org/stable/std/io/trait.Write.html#method.write_all "io::Write::write_all") method defined for I/O types by the [`Write`](https://doc.rust-lang.org/stable/std/io/trait.Write.html "io::Write") trait: use std::io; trait Write { fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io;%0A++++%0A++++trait+Write+%7B%0A++++++++fn+write_all(%26mut+self,+bytes:+%26%5Bu8%5D)+-%3E+Result%3C(),+io::Error%3E;%0A++++%7D%0A%7D&edition=2024 "Run code") _Note: The actual definition of [`Write`](https://doc.rust-lang.org/stable/std/io/trait.Write.html "io::Write") uses [`io::Result`](https://doc.rust-lang.org/stable/std/io/type.Result.html "io::Result") , which is just a synonym for `[Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") `._ This method doesn’t produce a value, but the write may fail. It’s crucial to handle the error case, and _not_ write something like this: use std::fs::File; use std::io::prelude::*; let mut file = File::create("valuable_data.txt").unwrap(); // If `write_all` errors, then we'll never know, because the return // value is ignored. file.write_all(b"important message"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A+//+%5Co/%0Afn+main()+%7B%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++%0A++++let+mut+file+=+File::create(%22valuable_data.txt%22).unwrap();%0A++++//+If+%60write_all%60+errors,+then+we%27ll+never+know,+because+the+return%0A++++//+value+is+ignored.%0A++++file.write_all(b%22important+message%22);%0A%7D&edition=2024 "Run code") If you _do_ write that in Rust, the compiler will give you a warning (by default, controlled by the `unused_must_use` lint). You might instead, if you don’t want to handle the error, simply assert success with [`expect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.expect "method std::result::Result::expect") . This will panic if the write fails, providing a marginally useful message indicating why: use std::fs::File; use std::io::prelude::*; let mut file = File::create("valuable_data.txt").unwrap(); file.write_all(b"important message").expect("failed to write message"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++%0A++++let+mut+file+=+File::create(%22valuable_data.txt%22).unwrap();%0A++++file.write_all(b%22important+message%22).expect(%22failed+to+write+message%22);%0A%7D&edition=2024 "Run code") You might also simply assert success: assert!(file.write_all(b"important message").is_ok()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++let+mut+file+=+File::create(%22valuable_data.txt%22).unwrap();%0A++++assert!(file.write_all(b%22important+message%22).is_ok());%0A%7D&edition=2024 "Run code") Or propagate the error up the call stack with [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") : fn write_message() -> io::Result<()> { let mut file = File::create("valuable_data.txt")?; file.write_all(b"important message")?; Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++use+std::io;%0A++++%23%5Ballow(dead_code)%5D%0A++++fn+write_message()+-%3E+io::Result%3C()%3E+%7B%0A++++++++let+mut+file+=+File::create(%22valuable_data.txt%22)?;%0A++++++++file.write_all(b%22important+message%22)?;%0A++++++++Ok(())%0A++++%7D%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/result/index.html#the-question-mark-operator-) The question mark operator, `?` ----------------------------------------------------------------------------------------------------------------------- When writing code that calls many functions that return the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") type, the error handling can be tedious. The question mark operator, [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , hides some of the boilerplate of propagating errors up the call stack. It replaces this: use std::fs::File; use std::io::prelude::*; use std::io; struct Info { name: String, age: i32, rating: i32, } fn write_info(info: &Info) -> io::Result<()> { // Early return on error let mut file = match File::create("my_best_friends.txt") { Err(e) => return Err(e), Ok(f) => f, }; if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) { return Err(e) } if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) { return Err(e) } if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) { return Err(e) } Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++use+std::io;%0A++++%0A++++struct+Info+%7B%0A++++++++name:+String,%0A++++++++age:+i32,%0A++++++++rating:+i32,%0A++++%7D%0A++++%0A++++fn+write_info(info:+%26Info)+-%3E+io::Result%3C()%3E+%7B%0A++++++++//+Early+return+on+error%0A++++++++let+mut+file+=+match+File::create(%22my_best_friends.txt%22)+%7B%0A+++++++++++++++Err(e)+=%3E+return+Err(e),%0A+++++++++++++++Ok(f)+=%3E+f,%0A++++++++%7D;%0A++++++++if+let+Err(e)+=+file.write_all(format!(%22name:+%7B%7D%5Cn%22,+info.name).as_bytes())+%7B%0A++++++++++++return+Err(e)%0A++++++++%7D%0A++++++++if+let+Err(e)+=+file.write_all(format!(%22age:+%7B%7D%5Cn%22,+info.age).as_bytes())+%7B%0A++++++++++++return+Err(e)%0A++++++++%7D%0A++++++++if+let+Err(e)+=+file.write_all(format!(%22rating:+%7B%7D%5Cn%22,+info.rating).as_bytes())+%7B%0A++++++++++++return+Err(e)%0A++++++++%7D%0A++++++++Ok(())%0A++++%7D%0A%7D&edition=2024 "Run code") With this: use std::fs::File; use std::io::prelude::*; use std::io; struct Info { name: String, age: i32, rating: i32, } fn write_info(info: &Info) -> io::Result<()> { let mut file = File::create("my_best_friends.txt")?; // Early return on error file.write_all(format!("name: {}\n", info.name).as_bytes())?; file.write_all(format!("age: {}\n", info.age).as_bytes())?; file.write_all(format!("rating: {}\n", info.rating).as_bytes())?; Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++use+std::io;%0A++++%0A++++struct+Info+%7B%0A++++++++name:+String,%0A++++++++age:+i32,%0A++++++++rating:+i32,%0A++++%7D%0A++++%0A++++fn+write_info(info:+%26Info)+-%3E+io::Result%3C()%3E+%7B%0A++++++++let+mut+file+=+File::create(%22my_best_friends.txt%22)?;%0A++++++++//+Early+return+on+error%0A++++++++file.write_all(format!(%22name:+%7B%7D%5Cn%22,+info.name).as_bytes())?;%0A++++++++file.write_all(format!(%22age:+%7B%7D%5Cn%22,+info.age).as_bytes())?;%0A++++++++file.write_all(format!(%22rating:+%7B%7D%5Cn%22,+info.rating).as_bytes())?;%0A++++++++Ok(())%0A++++%7D%0A%7D&edition=2024 "Run code") _It’s much nicer!_ Ending the expression with [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") will result in the [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") ’s unwrapped value, unless the result is [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") , in which case [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") is returned early from the enclosing function. [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") can be used in functions that return [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") because of the early return of [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") that it provides. [§](https://doc.rust-lang.org/stable/std/result/index.html#representation) Representation ----------------------------------------------------------------------------------------- In some cases, [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") comes with size, alignment, and ABI guarantees. Specifically, one of either the `T` or `E` type must be a type that qualifies for the `Option` [representation guarantees](https://doc.rust-lang.org/stable/std/option/index.html#representation "Option Representation") (let’s call that type `I`), and the _other_ type is a zero-sized type with alignment 1 (a “1-ZST”). If that is the case, then `Result` has the same size, alignment, and [function call ABI](https://doc.rust-lang.org/stable/std/primitive.fn.html#abi-compatibility) as `I` (and therefore, as `Option`). If `I` is `T`, it is therefore sound to transmute a value `t` of type `I` to type `Result` (producing the value `Ok(t)`) and to transmute a value `Ok(t)` of type `Result` to type `I` (producing the value `t`). If `I` is `E`, the same applies with `Ok` replaced by `Err`. For example, `NonZeroI32` qualifies for the `Option` representation guarantees and `()` is a zero-sized type with alignment 1. This means that both `Result` and `Result<(), NonZeroI32>` have the same size, alignment, and ABI as `NonZeroI32` (and `Option`). The only difference between these is in the implied semantics: * `Option` is “a non-zero i32 might be present” * `Result` is “a non-zero i32 success result, if any” * `Result<(), NonZeroI32>` is “a non-zero i32 error result, if any” [§](https://doc.rust-lang.org/stable/std/result/index.html#method-overview) Method overview ------------------------------------------------------------------------------------------- In addition to working with pattern matching, [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") provides a wide variety of different methods. ### [§](https://doc.rust-lang.org/stable/std/result/index.html#querying-the-variant) Querying the variant The [`is_ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_ok "method std::result::Result::is_ok") and [`is_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_err "method std::result::Result::is_err") methods return [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") or [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") , respectively. The [`is_ok_and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_ok_and "method std::result::Result::is_ok_and") and [`is_err_and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.is_err_and "method std::result::Result::is_err_and") methods apply the provided function to the contents of the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") to produce a boolean value. If the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") does not have the expected variant then [`false`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") is returned instead without executing the function. ### [§](https://doc.rust-lang.org/stable/std/result/index.html#adapters-for-working-with-references) Adapters for working with references * [`as_ref`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.as_ref "method std::result::Result::as_ref") converts from `&Result` to `Result<&T, &E>` * [`as_mut`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.as_mut "method std::result::Result::as_mut") converts from `&mut Result` to `Result<&mut T, &mut E>` * [`as_deref`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.as_deref "method std::result::Result::as_deref") converts from `&Result` to `Result<&T::Target, &E>` * [`as_deref_mut`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.as_deref_mut "method std::result::Result::as_deref_mut") converts from `&mut Result` to `Result<&mut T::Target, &mut E>` ### [§](https://doc.rust-lang.org/stable/std/result/index.html#extracting-contained-values) Extracting contained values These methods extract the contained value in a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") when it is the [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") variant. If the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") : * [`expect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.expect "method std::result::Result::expect") panics with a provided custom message * [`unwrap`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap "method std::result::Result::unwrap") panics with a generic message * [`unwrap_or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_or "method std::result::Result::unwrap_or") returns the provided default value * [`unwrap_or_default`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_or_default "method std::result::Result::unwrap_or_default") returns the default value of the type `T` (which must implement the [`Default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") trait) * [`unwrap_or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_or_else "method std::result::Result::unwrap_or_else") returns the result of evaluating the provided function * [`unwrap_unchecked`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_unchecked "method std::result::Result::unwrap_unchecked") produces _[undefined behavior](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) _ The panicking methods [`expect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.expect "method std::result::Result::expect") and [`unwrap`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap "method std::result::Result::unwrap") require `E` to implement the [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") trait. These methods extract the contained value in a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") when it is the [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") variant. They require `T` to implement the [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") trait. If the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") : * [`expect_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.expect_err "method std::result::Result::expect_err") panics with a provided custom message * [`unwrap_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_err "method std::result::Result::unwrap_err") panics with a generic message * [`unwrap_err_unchecked`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_err_unchecked "method std::result::Result::unwrap_err_unchecked") produces _[undefined behavior](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) _ ### [§](https://doc.rust-lang.org/stable/std/result/index.html#transforming-contained-values) Transforming contained values These methods transform [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") to [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") : * [`err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.err "method std::result::Result::err") transforms [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") into [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , mapping [`Err(e)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") to [`Some(e)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") and [`Ok(v)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") to [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.ok "method std::result::Result::ok") transforms [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") into [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , mapping [`Ok(v)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") to [`Some(v)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") and [`Err(e)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") to [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`transpose`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.transpose "method std::result::Result::transpose") transposes a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") into an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") of a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") These methods transform the contained value of the [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") variant: * [`map`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.map "method std::result::Result::map") transforms [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") into [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") by applying the provided function to the contained value of [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") and leaving [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") values unchanged * [`inspect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect "method std::result::Result::inspect") takes ownership of the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") , applies the provided function to the contained value by reference, and then returns the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") These methods transform the contained value of the [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") variant: * [`map_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.map_err "method std::result::Result::map_err") transforms [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") into [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") by applying the provided function to the contained value of [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") and leaving [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") values unchanged * [`inspect_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect_err "method std::result::Result::inspect_err") takes ownership of the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") , applies the provided function to the contained value of [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") by reference, and then returns the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") These methods transform a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") into a value of a possibly different type `U`: * [`map_or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.map_or "method std::result::Result::map_or") applies the provided function to the contained value of [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") , or returns the provided default value if the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") * [`map_or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.map_or_else "method std::result::Result::map_or_else") applies the provided function to the contained value of [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") , or applies the provided default fallback function to the contained value of [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") ### [§](https://doc.rust-lang.org/stable/std/result/index.html#boolean-operators) Boolean operators These methods treat the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") as a boolean value, where [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") acts like [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") and [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") acts like [`false`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") . There are two categories of these methods: ones that take a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") as input, and ones that take a function as input (to be lazily evaluated). The [`and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and "method std::result::Result::and") and [`or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or "method std::result::Result::or") methods take another [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") as input, and produce a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") as output. The [`and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and "method std::result::Result::and") method can produce a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") value having a different inner type `U` than [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . The [`or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or "method std::result::Result::or") method can produce a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") value having a different error type `F` than [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . | method | self | input | output | | --- | --- | --- | --- | | [`and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and "method std::result::Result::and") | `Err(e)` | (ignored) | `Err(e)` | | [`and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and "method std::result::Result::and") | `Ok(x)` | `Err(d)` | `Err(d)` | | [`and`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and "method std::result::Result::and") | `Ok(x)` | `Ok(y)` | `Ok(y)` | | [`or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or "method std::result::Result::or") | `Err(e)` | `Err(d)` | `Err(d)` | | [`or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or "method std::result::Result::or") | `Err(e)` | `Ok(y)` | `Ok(y)` | | [`or`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or "method std::result::Result::or") | `Ok(x)` | (ignored) | `Ok(x)` | The [`and_then`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and_then "method std::result::Result::and_then") and [`or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or_else "method std::result::Result::or_else") methods take a function as input, and only evaluate the function when they need to produce a new value. The [`and_then`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and_then "method std::result::Result::and_then") method can produce a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") value having a different inner type `U` than [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . The [`or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or_else "method std::result::Result::or_else") method can produce a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") value having a different error type `F` than [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . | method | self | function input | function result | output | | --- | --- | --- | --- | --- | | [`and_then`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and_then "method std::result::Result::and_then") | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` | | [`and_then`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and_then "method std::result::Result::and_then") | `Ok(x)` | `x` | `Err(d)` | `Err(d)` | | [`and_then`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and_then "method std::result::Result::and_then") | `Ok(x)` | `x` | `Ok(y)` | `Ok(y)` | | [`or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or_else "method std::result::Result::or_else") | `Err(e)` | `e` | `Err(d)` | `Err(d)` | | [`or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or_else "method std::result::Result::or_else") | `Err(e)` | `e` | `Ok(y)` | `Ok(y)` | | [`or_else`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.or_else "method std::result::Result::or_else") | `Ok(x)` | (not provided) | (not evaluated) | `Ok(x)` | ### [§](https://doc.rust-lang.org/stable/std/result/index.html#comparison-operators) Comparison operators If `T` and `E` both implement [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") then [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") will derive its [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") implementation. With this order, an [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") compares as less than any [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") , while two [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") or two [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") compare as their contained values would in `T` or `E` respectively. If `T` and `E` both also implement [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , then so does [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . assert!(Ok(1) < Err(0)); let x: Result = Ok(0); let y = Ok(1); assert!(x < y); let x: Result<(), i32> = Err(0); let y = Err(1); assert!(x < y); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert!(Ok(1)+%3C+Err(0));%0A++++let+x:+Result%3Ci32,+()%3E+=+Ok(0);%0A++++let+y+=+Ok(1);%0A++++assert!(x+%3C+y);%0A++++let+x:+Result%3C(),+i32%3E+=+Err(0);%0A++++let+y+=+Err(1);%0A++++assert!(x+%3C+y);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/result/index.html#iterating-over-result) Iterating over `Result` A [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") can be iterated over. This can be helpful if you need an iterator that is conditionally empty. The iterator will either produce a single value (when the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") ), or produce no values (when the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") ). For example, [`into_iter`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.into_iter "method std::result::Result::into_iter") acts like [`once(v)`](https://doc.rust-lang.org/stable/std/iter/fn.once.html "fn std::iter::once") if the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Ok(v)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") , and like [`empty()`](https://doc.rust-lang.org/stable/std/iter/fn.empty.html "fn std::iter::empty") if the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") is [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") . Iterators over [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") come in three types: * [`into_iter`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.into_iter "method std::result::Result::into_iter") consumes the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") and produces the contained value * [`iter`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.iter "method std::result::Result::iter") produces an immutable reference of type `&T` to the contained value * [`iter_mut`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.iter_mut "method std::result::Result::iter_mut") produces a mutable reference of type `&mut T` to the contained value See [Iterating over `Option`](https://doc.rust-lang.org/stable/std/option/index.html#iterating-over-option "mod std::option") for examples of how this can be useful. You might want to use an iterator chain to do multiple instances of an operation that can fail, but would like to ignore failures while continuing to process the successful results. In this example, we take advantage of the iterable nature of [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") to select only the [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") values using [`flatten`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flatten "method std::iter::Iterator::flatten") . let mut results = vec![]; let mut errs = vec![]; let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"] .into_iter() .map(u8::from_str) // Save clones of the raw `Result` values to inspect .inspect(|x| results.push(x.clone())) // Challenge: explain how this captures only the `Err` values .inspect(|x| errs.extend(x.clone().err())) .flatten() .collect(); assert_eq!(errs.len(), 3); assert_eq!(nums, [17, 99]); println!("results {results:?}"); println!("errs {errs:?}"); println!("nums {nums:?}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::str::FromStr;%0A++++let+mut+results+=+vec!%5B%5D;%0A++++let+mut+errs+=+vec!%5B%5D;%0A++++let+nums:+Vec%3C_%3E+=+%5B%2217%22,+%22not+a+number%22,+%2299%22,+%22-27%22,+%22768%22%5D%0A+++++++.into_iter()%0A+++++++.map(u8::from_str)%0A+++++++//+Save+clones+of+the+raw+%60Result%60+values+to+inspect%0A+++++++.inspect(%7Cx%7C+results.push(x.clone()))%0A+++++++//+Challenge:+explain+how+this+captures+only+the+%60Err%60+values%0A+++++++.inspect(%7Cx%7C+errs.extend(x.clone().err()))%0A+++++++.flatten()%0A+++++++.collect();%0A++++assert_eq!(errs.len(),+3);%0A++++assert_eq!(nums,+%5B17,+99%5D);%0A++++println!(%22results+%7Bresults:?%7D%22);%0A++++println!(%22errs+%7Berrs:?%7D%22);%0A++++println!(%22nums+%7Bnums:?%7D%22);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/result/index.html#collecting-into-result) Collecting into `Result` [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") implements the [`FromIterator`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#impl-FromIterator%3CResult%3CA,+E%3E%3E-for-Result%3CV,+E%3E "enum std::result::Result") trait, which allows an iterator over [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") values to be collected into a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") of a collection of each contained value of the original [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") values, or [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") if any of the elements was [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") . let v = [Ok(2), Ok(4), Err("err!"), Ok(8)]; let res: Result, &str> = v.into_iter().collect(); assert_eq!(res, Err("err!")); let v = [Ok(2), Ok(4), Ok(8)]; let res: Result, &str> = v.into_iter().collect(); assert_eq!(res, Ok(vec![2, 4, 8])); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v+=+%5BOk(2),+Ok(4),+Err(%22err!%22),+Ok(8)%5D;%0A++++let+res:+Result%3CVec%3C_%3E,+%26str%3E+=+v.into_iter().collect();%0A++++assert_eq!(res,+Err(%22err!%22));%0A++++let+v+=+%5BOk(2),+Ok(4),+Ok(8)%5D;%0A++++let+res:+Result%3CVec%3C_%3E,+%26str%3E+=+v.into_iter().collect();%0A++++assert_eq!(res,+Ok(vec!%5B2,+4,+8%5D));%0A%7D&edition=2024 "Run code") [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") also implements the [`Product`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#impl-Product%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E "enum std::result::Result") and [`Sum`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#impl-Sum%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E "enum std::result::Result") traits, allowing an iterator over [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") values to provide the [`product`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.product "method std::iter::Iterator::product") and [`sum`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.sum "method std::iter::Iterator::sum") methods. let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")]; let res: Result = v.into_iter().sum(); assert_eq!(res, Err("error!")); let v = [Ok(1), Ok(2), Ok(21)]; let res: Result = v.into_iter().product(); assert_eq!(res, Ok(42)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v+=+%5BErr(%22error!%22),+Ok(1),+Ok(2),+Ok(3),+Err(%22foo%22)%5D;%0A++++let+res:+Result%3Ci32,+%26str%3E+=+v.into_iter().sum();%0A++++assert_eq!(res,+Err(%22error!%22));%0A++++let+v+=+%5BOk(1),+Ok(2),+Ok(21)%5D;%0A++++let+res:+Result%3Ci32,+%26str%3E+=+v.into_iter().product();%0A++++assert_eq!(res,+Ok(42));%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/result/index.html#structs) --------------------------------------------------------------------------- [IntoIter](https://doc.rust-lang.org/stable/std/result/struct.IntoIter.html "struct std::result::IntoIter") An iterator over the value in a [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") variant of a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . [Iter](https://doc.rust-lang.org/stable/std/result/struct.Iter.html "struct std::result::Iter") An iterator over a reference to the [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") variant of a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . [IterMut](https://doc.rust-lang.org/stable/std/result/struct.IterMut.html "struct std::result::IterMut") An iterator over a mutable reference to the [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") variant of a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . Enums[§](https://doc.rust-lang.org/stable/std/result/index.html#enums) ----------------------------------------------------------------------- [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") `Result` is a type that represents either success ([`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") ) or failure ([`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") ). --- # std::backtrace - Rust [Module backtrace](https://doc.rust-lang.org/stable/std/backtrace/index.html#) ------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module backtrace Copy item path =============================== 1.65.0 · [Source](https://doc.rust-lang.org/stable/src/std/backtrace.rs.html#1-478) Expand description Support for capturing a stack backtrace of an OS thread This module contains the support necessary to capture a stack backtrace of a running OS thread from the OS thread itself. The `Backtrace` type supports capturing a stack trace via the `Backtrace::capture` and `Backtrace::force_capture` functions. A backtrace is typically quite handy to attach to errors (e.g. types implementing `std::error::Error`) to get a causal chain of where an error was generated. ### [§](https://doc.rust-lang.org/stable/std/backtrace/index.html#accuracy) Accuracy Backtraces are attempted to be as accurate as possible, but no guarantees are provided about the exact accuracy of a backtrace. Instruction pointers, symbol names, filenames, line numbers, etc, may all be incorrect when reported. Accuracy is attempted on a best-effort basis, however, any bug reports are always welcome to indicate areas of improvement! For most platforms a backtrace with a filename/line number requires that programs be compiled with debug information. Without debug information filenames/line numbers will not be reported. ### [§](https://doc.rust-lang.org/stable/std/backtrace/index.html#platform-support) Platform support Not all platforms that std compiles for support capturing backtraces. Some platforms simply do nothing when capturing a backtrace. To check whether the platform supports capturing backtraces you can consult the `BacktraceStatus` enum as a result of `Backtrace::status`. Like above with accuracy platform support is done on a best effort basis. Sometimes libraries might not be available at runtime or something may go wrong which would cause a backtrace to not be captured. Please feel free to report issues with platforms where a backtrace cannot be captured though! ### [§](https://doc.rust-lang.org/stable/std/backtrace/index.html#environment-variables) Environment Variables The `Backtrace::capture` function might not actually capture a backtrace by default. Its behavior is governed by two environment variables: * `RUST_LIB_BACKTRACE` - if this is set to `0` then `Backtrace::capture` will never capture a backtrace. Any other value set will enable `Backtrace::capture`. * `RUST_BACKTRACE` - if `RUST_LIB_BACKTRACE` is not set, then this variable is consulted with the same rules of `RUST_LIB_BACKTRACE`. * If neither of the above env vars are set, then `Backtrace::capture` will be disabled. Capturing a backtrace can be a quite expensive runtime operation, so the environment variables allow either forcibly disabling this runtime performance hit or allow selectively enabling it in some programs. Note that the `Backtrace::force_capture` function can be used to ignore these environment variables. Also note that the state of environment variables is cached once the first backtrace is created, so altering `RUST_LIB_BACKTRACE` or `RUST_BACKTRACE` at runtime might not actually change how backtraces are captured. Structs[§](https://doc.rust-lang.org/stable/std/backtrace/index.html#structs) ------------------------------------------------------------------------------ [Backtrace](https://doc.rust-lang.org/stable/std/backtrace/struct.Backtrace.html "struct std::backtrace::Backtrace") A captured OS thread stack backtrace. [BacktraceFrame](https://doc.rust-lang.org/stable/std/backtrace/struct.BacktraceFrame.html "struct std::backtrace::BacktraceFrame") Experimental A single frame of a backtrace. Enums[§](https://doc.rust-lang.org/stable/std/backtrace/index.html#enums) -------------------------------------------------------------------------- [BacktraceStatus](https://doc.rust-lang.org/stable/std/backtrace/enum.BacktraceStatus.html "enum std::backtrace::BacktraceStatus") The current status of a backtrace, indicating whether it was captured or whether it is empty for some other reason. --- # std::any - Rust [Module any](https://doc.rust-lang.org/stable/std/any/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module any Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#301) Expand description Utilities for dynamic typing or type reflection. [§](https://doc.rust-lang.org/stable/std/any/index.html#any-and-typeid) `Any` and `TypeId` ------------------------------------------------------------------------------------------ `Any` itself can be used to get a `TypeId`, and has more features when used as a trait object. As `&dyn Any` (a borrowed trait object), it has the `is` and `downcast_ref` methods, to test if the contained value is of a given type, and to get a reference to the inner value as a type. As `&mut dyn Any`, there is also the `downcast_mut` method, for getting a mutable reference to the inner value. `Box` adds the `downcast` method, which attempts to convert to a `Box`. See the [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) documentation for the full details. Note that `&dyn Any` is limited to testing whether a value is of a specified concrete type, and cannot be used to test whether a type implements a trait. [§](https://doc.rust-lang.org/stable/std/any/index.html#smart-pointers-and-dyn-any) Smart pointers and `dyn Any` ---------------------------------------------------------------------------------------------------------------- One piece of behavior to keep in mind when using `Any` as a trait object, especially with types like `Box` or `Arc`, is that simply calling `.type_id()` on the value will produce the `TypeId` of the _container_, not the underlying trait object. This can be avoided by converting the smart pointer into a `&dyn Any` instead, which will return the object’s `TypeId`. For example: use std::any::{Any, TypeId}; let boxed: Box = Box::new(3_i32); // You're more likely to want this: let actual_id = (&*boxed).type_id(); // ... than this: let boxed_id = boxed.type_id(); assert_eq!(actual_id, TypeId::of::()); assert_eq!(boxed_id, TypeId::of::>()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::%7BAny,+TypeId%7D;%0A++++%0A++++let+boxed:+Box%3Cdyn+Any%3E+=+Box::new(3_i32);%0A++++%0A++++//+You%27re+more+likely+to+want+this:%0A++++let+actual_id+=+(%26*boxed).type_id();%0A++++//+...+than+this:%0A++++let+boxed_id+=+boxed.type_id();%0A++++%0A++++assert_eq!(actual_id,+TypeId::of::%3Ci32%3E());%0A++++assert_eq!(boxed_id,+TypeId::of::%3CBox%3Cdyn+Any%3E%3E());%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/any/index.html#examples) Examples Consider a situation where we want to log a value passed to a function. We know the value we’re working on implements `Debug`, but we don’t know its concrete type. We want to give special treatment to certain types: in this case printing out the length of `String` values prior to their value. We don’t know the concrete type of our value at compile time, so we need to use runtime reflection instead. use std::fmt::Debug; use std::any::Any; // Logger function for any type that implements `Debug`. fn log(value: &T) { let value_any = value as &dyn Any; // Try to convert our value to a `String`. If successful, we want to // output the `String`'s length as well as its value. If not, it's a // different type: just print it out unadorned. match value_any.downcast_ref::() { Some(as_string) => { println!("String ({}): {}", as_string.len(), as_string); } None => { println!("{value:?}"); } } } // This function wants to log its parameter out prior to doing work with it. fn do_work(value: &T) { log(value); // ...do some other work } fn main() { let my_string = "Hello World".to_string(); do_work(&my_string); let my_i8: i8 = 100; do_work(&my_i8); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::fmt::Debug;%0Ause+std::any::Any;%0A%0A//+Logger+function+for+any+type+that+implements+%60Debug%60.%0Afn+log%3CT:+Any+%2B+Debug%3E(value:+%26T)+%7B%0A++++let+value_any+=+value+as+%26dyn+Any;%0A%0A++++//+Try+to+convert+our+value+to+a+%60String%60.+If+successful,+we+want+to%0A++++//+output+the+%60String%60%27s+length+as+well+as+its+value.+If+not,+it%27s+a%0A++++//+different+type:+just+print+it+out+unadorned.%0A++++match+value_any.downcast_ref::%3CString%3E()+%7B%0A++++++++Some(as_string)+=%3E+%7B%0A++++++++++++println!(%22String+(%7B%7D):+%7B%7D%22,+as_string.len(),+as_string);%0A++++++++%7D%0A++++++++None+=%3E+%7B%0A++++++++++++println!(%22%7Bvalue:?%7D%22);%0A++++++++%7D%0A++++%7D%0A%7D%0A%0A//+This+function+wants+to+log+its+parameter+out+prior+to+doing+work+with+it.%0Afn+do_work%3CT:+Any+%2B+Debug%3E(value:+%26T)+%7B%0A++++log(value);%0A++++//+...do+some+other+work%0A%7D%0A%0Afn+main()+%7B%0A++++let+my_string+=+%22Hello+World%22.to_string();%0A++++do_work(%26my_string);%0A%0A++++let+my_i8:+i8+=+100;%0A++++do_work(%26my_i8);%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/any/index.html#structs) ------------------------------------------------------------------------ [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") A `TypeId` represents a globally unique identifier for a type. Traits[§](https://doc.rust-lang.org/stable/std/any/index.html#traits) ---------------------------------------------------------------------- [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") A trait to emulate dynamic typing. Functions[§](https://doc.rust-lang.org/stable/std/any/index.html#functions) ---------------------------------------------------------------------------- [type\_name](https://doc.rust-lang.org/stable/std/any/fn.type_name.html "fn std::any::type_name") Returns the name of a type as a string slice. [type\_name\_of\_val](https://doc.rust-lang.org/stable/std/any/fn.type_name_of_val.html "fn std::any::type_name_of_val") Returns the type name of the pointed-to value as a string slice. --- # std::ascii - Rust [Module ascii](https://doc.rust-lang.org/stable/std/ascii/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module ascii Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ascii.rs.html#1-210) Expand description Operations on ASCII strings and characters. Most string operations in Rust act on UTF-8 strings. However, at times it makes more sense to only consider the ASCII character set for a specific operation. The [`AsciiExt`](https://doc.rust-lang.org/stable/std/ascii/trait.AsciiExt.html "trait std::ascii::AsciiExt") trait provides methods that allow for character operations that only act on the ASCII subset and leave non-ASCII characters alone. The [`escape_default`](https://doc.rust-lang.org/stable/std/ascii/fn.escape_default.html "fn std::ascii::escape_default") function provides an iterator over the bytes of an escaped version of the character given. Structs[§](https://doc.rust-lang.org/stable/std/ascii/index.html#structs) -------------------------------------------------------------------------- [EscapeDefault](https://doc.rust-lang.org/stable/std/ascii/struct.EscapeDefault.html "struct std::ascii::EscapeDefault") An iterator over the escaped version of a byte. Enums[§](https://doc.rust-lang.org/stable/std/ascii/index.html#enums) ---------------------------------------------------------------------- [Char](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") Experimental One of the 128 Unicode characters from U+0000 through U+007F, often known as the [ASCII](https://www.unicode.org/glossary/index.html#ASCII) subset. Traits[§](https://doc.rust-lang.org/stable/std/ascii/index.html#traits) ------------------------------------------------------------------------ [AsciiExt](https://doc.rust-lang.org/stable/std/ascii/trait.AsciiExt.html "trait std::ascii::AsciiExt") Deprecated Extension methods for ASCII-subset only operations. Functions[§](https://doc.rust-lang.org/stable/std/ascii/index.html#functions) ------------------------------------------------------------------------------ [escape\_default](https://doc.rust-lang.org/stable/std/ascii/fn.escape_default.html "fn std::ascii::escape_default") Returns an iterator that produces an escaped version of a `u8`. --- # std::borrow - Rust [Module borrow](https://doc.rust-lang.org/stable/std/borrow/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module borrow Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#213) Expand description A module for working with borrowed data. Enums[§](https://doc.rust-lang.org/stable/std/borrow/index.html#enums) ----------------------------------------------------------------------- [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") A clone-on-write smart pointer. Traits[§](https://doc.rust-lang.org/stable/std/borrow/index.html#traits) ------------------------------------------------------------------------- [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") A trait for borrowing data. [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") A trait for mutably borrowing data. [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") A generalization of `Clone` to borrowed data. --- # std::i8 - Rust [Module i8](https://doc.rust-lang.org/stable/std/i8/index.html#) ----------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module i8 Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#64) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`i8` primitive type](https://doc.rust-lang.org/stable/std/primitive.i8.html "primitive i8") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/i8/index.html#constants) --------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/i8/constant.MAX.html "constant std::i8::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`i8::MAX`](https://doc.rust-lang.org/stable/std/primitive.i8.html#associatedconstant.MAX "associated constant i8::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/i8/constant.MIN.html "constant std::i8::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`i8::MIN`](https://doc.rust-lang.org/stable/std/primitive.i8.html#associatedconstant.MIN "associated constant i8::MIN") instead. --- # std::thread - Rust [Module thread](https://doc.rust-lang.org/stable/std/thread/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module thread Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/mod.rs.html#1-2097) Expand description Native threads. ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#the-threading-model) The threading model An executing Rust program consists of a collection of native OS threads, each with their own stack and local state. Threads can be named, and provide some built-in support for low-level synchronization. Communication between threads can be done through [channels](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html "mod std::sync::mpsc") , Rust’s message-passing types, along with [other forms of thread synchronization](https://doc.rust-lang.org/stable/std/sync/index.html) and shared-memory data structures. In particular, types that are guaranteed to be threadsafe are easily shared between threads using the atomically-reference-counted container, [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") . Fatal logic errors in Rust cause _thread panic_, during which a thread will unwind the stack, running destructors and freeing owned resources. While not meant as a ‘try/catch’ mechanism, panics in Rust can nonetheless be caught (unless compiling with `panic=abort`) with [`catch_unwind`](https://doc.rust-lang.org/stable/std/panic/fn.catch_unwind.html) and recovered from, or alternatively be resumed with [`resume_unwind`](https://doc.rust-lang.org/stable/std/panic/fn.resume_unwind.html) . If the panic is not caught the thread will exit, but the panic may optionally be detected from a different thread with [`join`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join "method std::thread::JoinHandle::join") . If the main thread panics without the panic being caught, the application will exit with a non-zero exit code. When the main thread of a Rust program terminates, the entire program shuts down, even if other threads are still running. However, this module provides convenient facilities for automatically waiting for the termination of a thread (i.e., join). ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#spawning-a-thread) Spawning a thread A new thread can be spawned using the [`thread::spawn`](https://doc.rust-lang.org/stable/std/thread/fn.spawn.html "fn std::thread::spawn") function: use std::thread; thread::spawn(move || { // some work here }); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++//+some+work+here%0A++++%7D);%0A%7D&edition=2024 "Run code") In this example, the spawned thread is “detached,” which means that there is no way for the program to learn when the spawned thread completes or otherwise terminates. To learn when a thread completes, it is necessary to capture the [`JoinHandle`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html "struct std::thread::JoinHandle") object that is returned by the call to [`spawn`](https://doc.rust-lang.org/stable/std/thread/fn.spawn.html "fn std::thread::spawn") , which provides a `join` method that allows the caller to wait for the completion of the spawned thread: use std::thread; let thread_join_handle = thread::spawn(move || { // some work here }); // some work here let res = thread_join_handle.join(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++%0A++++let+thread_join_handle+=+thread::spawn(move+%7C%7C+%7B%0A++++++++//+some+work+here%0A++++%7D);%0A++++//+some+work+here%0A++++let+res+=+thread_join_handle.join();%0A%7D&edition=2024 "Run code") The [`join`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join "method std::thread::JoinHandle::join") method returns a [`thread::Result`](https://doc.rust-lang.org/stable/std/thread/type.Result.html "type std::thread::Result") containing [`Ok`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") of the final value produced by the spawned thread, or [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") of the value given to a call to [`panic!`](https://doc.rust-lang.org/stable/std/macro.panic.html "macro std::panic") if the thread panicked. Note that there is no parent/child relationship between a thread that spawns a new thread and the thread being spawned. In particular, the spawned thread may or may not outlive the spawning thread, unless the spawning thread is the main thread. ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#configuring-threads) Configuring threads A new thread can be configured before it is spawned via the [`Builder`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html "struct std::thread::Builder") type, which currently allows you to set the name and stack size for the thread: use std::thread; thread::Builder::new().name("thread1".to_string()).spawn(move || { println!("Hello, world!"); }); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++use+std::thread;%0A++++%0A++++thread::Builder::new().name(%22thread1%22.to_string()).spawn(move+%7C%7C+%7B%0A++++++++println!(%22Hello,+world!%22);%0A++++%7D);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#the-thread-type) The `Thread` type Threads are represented via the [`Thread`](https://doc.rust-lang.org/stable/std/thread/struct.Thread.html "struct std::thread::Thread") type, which you can get in one of two ways: * By spawning a new thread, e.g., using the [`thread::spawn`](https://doc.rust-lang.org/stable/std/thread/fn.spawn.html "fn std::thread::spawn") function, and calling [`thread`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.thread "method std::thread::JoinHandle::thread") on the [`JoinHandle`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html "struct std::thread::JoinHandle") . * By requesting the current thread, using the [`thread::current`](https://doc.rust-lang.org/stable/std/thread/fn.current.html "fn std::thread::current") function. The [`thread::current`](https://doc.rust-lang.org/stable/std/thread/fn.current.html "fn std::thread::current") function is available even for threads not spawned by the APIs of this module. ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#thread-local-storage) Thread-local storage This module also provides an implementation of thread-local storage for Rust programs. Thread-local storage is a method of storing data into a global variable that each thread in the program will have its own copy of. Threads do not share this data, so accesses do not need to be synchronized. A thread-local key owns the value it contains and will destroy the value when the thread exits. It is created with the [`thread_local!`](https://doc.rust-lang.org/stable/std/macro.thread_local.html "macro std::thread_local") macro and can contain any value that is `'static` (no borrowed pointers). It provides an accessor function, [`with`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with "method std::thread::LocalKey::with") , that yields a shared reference to the value to the specified closure. Thread-local keys allow only shared access to values, as there would be no way to guarantee uniqueness if mutable borrows were allowed. Most values will want to make use of some form of **interior mutability** through the [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") or [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") types. ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#naming-threads) Naming threads Threads are able to have associated names for identification purposes. By default, spawned threads are unnamed. To specify a name for a thread, build the thread with [`Builder`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html "struct std::thread::Builder") and pass the desired thread name to [`Builder::name`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html#method.name "method std::thread::Builder::name") . To retrieve the thread name from within the thread, use [`Thread::name`](https://doc.rust-lang.org/stable/std/thread/struct.Thread.html#method.name "method std::thread::Thread::name") . A couple of examples where the name of a thread gets used: * If a panic occurs in a named thread, the thread name will be printed in the panic message. * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in unix-like platforms). ### [§](https://doc.rust-lang.org/stable/std/thread/index.html#stack-size) Stack size The default stack size is platform-dependent and subject to change. Currently, it is 2 MiB on all Tier-1 platforms. There are two ways to manually specify the stack size for spawned threads: * Build the thread with [`Builder`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html "struct std::thread::Builder") and pass the desired stack size to [`Builder::stack_size`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html#method.stack_size "method std::thread::Builder::stack_size") . * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack size (in bytes). Note that setting [`Builder::stack_size`](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html#method.stack_size "method std::thread::Builder::stack_size") will override this. Be aware that changes to `RUST_MIN_STACK` may be ignored after program start. Note that the stack size of the main thread is _not_ determined by Rust. Structs[§](https://doc.rust-lang.org/stable/std/thread/index.html#structs) --------------------------------------------------------------------------- [AccessError](https://doc.rust-lang.org/stable/std/thread/struct.AccessError.html "struct std::thread::AccessError") An error returned by [`LocalKey::try_with`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.try_with) . [Builder](https://doc.rust-lang.org/stable/std/thread/struct.Builder.html "struct std::thread::Builder") Thread factory, which can be used in order to configure the properties of a new thread. [JoinHandle](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html "struct std::thread::JoinHandle") An owned permission to join on a thread (block on its termination). [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") A thread local storage (TLS) key which owns its contents. [Scope](https://doc.rust-lang.org/stable/std/thread/struct.Scope.html "struct std::thread::Scope") A scope to spawn scoped threads in. [ScopedJoinHandle](https://doc.rust-lang.org/stable/std/thread/struct.ScopedJoinHandle.html "struct std::thread::ScopedJoinHandle") An owned permission to join on a scoped thread (block on its termination). [Thread](https://doc.rust-lang.org/stable/std/thread/struct.Thread.html "struct std::thread::Thread") A handle to a thread. [ThreadId](https://doc.rust-lang.org/stable/std/thread/struct.ThreadId.html "struct std::thread::ThreadId") A unique identifier for a running thread. Functions[§](https://doc.rust-lang.org/stable/std/thread/index.html#functions) ------------------------------------------------------------------------------- [available\_parallelism](https://doc.rust-lang.org/stable/std/thread/fn.available_parallelism.html "fn std::thread::available_parallelism") Returns an estimate of the default amount of parallelism a program should use. [current](https://doc.rust-lang.org/stable/std/thread/fn.current.html "fn std::thread::current") Gets a handle to the thread that invokes it. [panicking](https://doc.rust-lang.org/stable/std/thread/fn.panicking.html "fn std::thread::panicking") Determines whether the current thread is unwinding because of panic. [park](https://doc.rust-lang.org/stable/std/thread/fn.park.html "fn std::thread::park") Blocks unless or until the current thread’s token is made available. [park\_timeout](https://doc.rust-lang.org/stable/std/thread/fn.park_timeout.html "fn std::thread::park_timeout") Blocks unless or until the current thread’s token is made available or the specified duration has been reached (may wake spuriously). [park\_timeout\_ms](https://doc.rust-lang.org/stable/std/thread/fn.park_timeout_ms.html "fn std::thread::park_timeout_ms") Deprecated Uses [`park_timeout`](https://doc.rust-lang.org/stable/std/thread/fn.park_timeout.html "fn std::thread::park_timeout") . [scope](https://doc.rust-lang.org/stable/std/thread/fn.scope.html "fn std::thread::scope") Creates a scope for spawning scoped threads. [sleep](https://doc.rust-lang.org/stable/std/thread/fn.sleep.html "fn std::thread::sleep") Puts the current thread to sleep for at least the specified amount of time. [sleep\_ms](https://doc.rust-lang.org/stable/std/thread/fn.sleep_ms.html "fn std::thread::sleep_ms") Deprecated Uses [`sleep`](https://doc.rust-lang.org/stable/std/thread/fn.sleep.html "fn std::thread::sleep") . [spawn](https://doc.rust-lang.org/stable/std/thread/fn.spawn.html "fn std::thread::spawn") Spawns a new thread, returning a [`JoinHandle`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html "struct std::thread::JoinHandle") for it. [yield\_now](https://doc.rust-lang.org/stable/std/thread/fn.yield_now.html "fn std::thread::yield_now") Cooperatively gives up a timeslice to the OS scheduler. [add\_spawn\_hook](https://doc.rust-lang.org/stable/std/thread/fn.add_spawn_hook.html "fn std::thread::add_spawn_hook") Experimental Registers a function to run for every newly thread spawned. [current\_id](https://doc.rust-lang.org/stable/std/thread/fn.current_id.html "fn std::thread::current_id") Experimental Gets the unique identifier of the thread which invokes it. [sleep\_until](https://doc.rust-lang.org/stable/std/thread/fn.sleep_until.html "fn std::thread::sleep_until") Experimental Puts the current thread to sleep until the specified deadline has passed. Type Aliases[§](https://doc.rust-lang.org/stable/std/thread/index.html#types) ------------------------------------------------------------------------------ [Result](https://doc.rust-lang.org/stable/std/thread/type.Result.html "type std::thread::Result") A specialized [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") type for threads. --- # std::i16 - Rust [Module i16](https://doc.rust-lang.org/stable/std/i16/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module i16 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#61) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`i16` primitive type](https://doc.rust-lang.org/stable/std/primitive.i16.html "primitive i16") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/i16/index.html#constants) ---------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/i16/constant.MAX.html "constant std::i16::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`i16::MAX`](https://doc.rust-lang.org/stable/std/primitive.i16.html#associatedconstant.MAX "associated constant i16::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/i16/constant.MIN.html "constant std::i16::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`i16::MIN`](https://doc.rust-lang.org/stable/std/primitive.i16.html#associatedconstant.MIN "associated constant i16::MIN") instead. --- # std::i32 - Rust [Module i32](https://doc.rust-lang.org/stable/std/i32/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module i32 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#62) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`i32` primitive type](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive i32") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/i32/index.html#constants) ---------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/i32/constant.MAX.html "constant std::i32::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`i32::MAX`](https://doc.rust-lang.org/stable/std/primitive.i32.html#associatedconstant.MAX "associated constant i32::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/i32/constant.MIN.html "constant std::i32::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`i32::MIN`](https://doc.rust-lang.org/stable/std/primitive.i32.html#associatedconstant.MIN "associated constant i32::MIN") instead. --- # std::i64 - Rust [Module i64](https://doc.rust-lang.org/stable/std/i64/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module i64 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#63) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`i64` primitive type](https://doc.rust-lang.org/stable/std/primitive.i64.html "primitive i64") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/i64/index.html#constants) ---------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/i64/constant.MAX.html "constant std::i64::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`i64::MAX`](https://doc.rust-lang.org/stable/std/primitive.i64.html#associatedconstant.MAX "associated constant i64::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/i64/constant.MIN.html "constant std::i64::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`i64::MIN`](https://doc.rust-lang.org/stable/std/primitive.i64.html#associatedconstant.MIN "associated constant i64::MIN") instead. --- # std::i128 - Rust [Module i128](https://doc.rust-lang.org/stable/std/i128/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module i128 Copy item path ========================== 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#60) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`i128` primitive type](https://doc.rust-lang.org/stable/std/primitive.i128.html "primitive i128") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/i128/index.html#constants) ----------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/i128/constant.MAX.html "constant std::i128::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`i128::MAX`](https://doc.rust-lang.org/stable/std/primitive.i128.html#associatedconstant.MAX "associated constant i128::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/i128/constant.MIN.html "constant std::i128::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`i128::MIN`](https://doc.rust-lang.org/stable/std/primitive.i128.html#associatedconstant.MIN "associated constant i128::MIN") instead. --- # std::isize - Rust [Module isize](https://doc.rust-lang.org/stable/std/isize/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module isize Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#65) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`isize` primitive type](https://doc.rust-lang.org/stable/std/primitive.isize.html "primitive isize") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/isize/index.html#constants) ------------------------------------------------------------------------------ [MAX](https://doc.rust-lang.org/stable/std/isize/constant.MAX.html "constant std::isize::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`isize::MAX`](https://doc.rust-lang.org/stable/std/primitive.isize.html#associatedconstant.MAX "associated constant isize::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/isize/constant.MIN.html "constant std::isize::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`isize::MIN`](https://doc.rust-lang.org/stable/std/primitive.isize.html#associatedconstant.MIN "associated constant isize::MIN") instead. --- # std::clone - Rust [Module clone](https://doc.rust-lang.org/stable/std/clone/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module clone Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#291) Expand description The `Clone` trait for types that cannot be ‘implicitly copied’. In Rust, some simple types are “implicitly copyable” and when you assign them or pass them as arguments, the receiver will get a copy, leaving the original value in place. These types do not require allocation to copy and do not have finalizers (i.e., they do not contain owned boxes or implement [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") ), so the compiler considers them cheap and safe to copy. For other types copies must be made explicitly, by convention implementing the [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone "method std::clone::Clone::clone") trait and calling the [`clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone "method std::clone::Clone::clone") method. Basic usage example: let s = String::new(); // String type implements Clone let copy = s.clone(); // so we can clone it [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+s+=+String::new();+//+String+type+implements+Clone%0A++++let+copy+=+s.clone();%0A%7D&edition=2024 "Run code") To easily implement the Clone trait, you can also use `#[derive(Clone)]`. Example: #[derive(Clone)] // we add the Clone trait to Morpheus struct struct Morpheus { blue_pill: f32, red_pill: i64, } fn main() { let f = Morpheus { blue_pill: 0.0, red_pill: 0 }; let copy = f.clone(); // and now we can clone it! } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23%5Bderive(Clone)%5D+//+we+add+the+Clone+trait+to+Morpheus+struct%0Astruct+Morpheus+%7B%0A+++blue_pill:+f32,%0A+++red_pill:+i64,%0A%7D%0A%0Afn+main()+%7B%0A+++let+f+=+Morpheus+%7B+blue_pill:+0.0,+red_pill:+0+%7D;%0A+++let+copy+=+f.clone();+//+and+now+we+can+clone+it!%0A%7D&edition=2024 "Run code") Traits[§](https://doc.rust-lang.org/stable/std/clone/index.html#traits) ------------------------------------------------------------------------ [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") A common trait that allows explicit creation of a duplicate value. [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") Experimental A generalization of [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") to [dynamically-sized types](https://doc.rust-lang.org/reference/dynamically-sized-types.html) stored in arbitrary containers. [UseCloned](https://doc.rust-lang.org/stable/std/clone/trait.UseCloned.html "trait std::clone::UseCloned") Experimental Trait for objects whose [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") impl is lightweight (e.g. reference-counted) Derive Macros[§](https://doc.rust-lang.org/stable/std/clone/index.html#derives) -------------------------------------------------------------------------------- [Clone](https://doc.rust-lang.org/stable/std/clone/derive.Clone.html "derive std::clone::Clone") Derive macro generating an impl of the trait `Clone`. --- # std::option - Rust [Module option](https://doc.rust-lang.org/stable/std/option/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module option Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#316) Expand description Optional values. Type [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") represents an optional value: every [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is either [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") and contains a value, or [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") , and does not. [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") types are very common in Rust code, as they have a number of uses: * Initial values * Return values for functions that are not defined over their entire input range (partial functions) * Return value for otherwise reporting simple errors, where [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") is returned on error * Optional struct fields * Struct fields that can be loaned or “taken” * Optional function arguments * Nullable pointers * Swapping things out of difficult situations [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") s are commonly paired with pattern matching to query the presence of a value and take action, always accounting for the [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") case. fn divide(numerator: f64, denominator: f64) -> Option { if denominator == 0.0 { None } else { Some(numerator / denominator) } } // The return value of the function is an option let result = divide(2.0, 3.0); // Pattern match to retrieve the value match result { // The division was valid Some(x) => println!("Result: {x}"), // The division was invalid None => println!("Cannot divide by 0"), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+divide(numerator:+f64,+denominator:+f64)+-%3E+Option%3Cf64%3E+%7B%0A++++++++if+denominator+==+0.0+%7B%0A++++++++++++None%0A++++++++%7D+else+%7B%0A++++++++++++Some(numerator+/+denominator)%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+The+return+value+of+the+function+is+an+option%0A++++let+result+=+divide(2.0,+3.0);%0A++++%0A++++//+Pattern+match+to+retrieve+the+value%0A++++match+result+%7B%0A++++++++//+The+division+was+valid%0A++++++++Some(x)+=%3E+println!(%22Result:+%7Bx%7D%22),%0A++++++++//+The+division+was+invalid%0A++++++++None++++=%3E+println!(%22Cannot+divide+by+0%22),%0A++++%7D%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/option/index.html#options-and-pointers-nullable-pointers) Options and pointers (“nullable” pointers) --------------------------------------------------------------------------------------------------------------------------------------------- Rust’s pointer types must always point to a valid location; there are no “null” references. Instead, Rust has _optional_ pointers, like the optional owned box, `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) >`. The following example uses [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") to create an optional box of [`i32`](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive i32") . Notice that in order to use the inner [`i32`](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive i32") value, the `check_optional` function first needs to use pattern matching to determine whether the box has a value (i.e., it is [`Some(...)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") ) or not ([`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") ). let optional = None; check_optional(optional); let optional = Some(Box::new(9000)); check_optional(optional); fn check_optional(optional: Option>) { match optional { Some(p) => println!("has value {p}"), None => println!("has no value"), } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+optional+=+None;%0A++++check_optional(optional);%0A++++%0A++++let+optional+=+Some(Box::new(9000));%0A++++check_optional(optional);%0A++++%0A++++fn+check_optional(optional:+Option%3CBox%3Ci32%3E%3E)+%7B%0A++++++++match+optional+%7B%0A++++++++++++Some(p)+=%3E+println!(%22has+value+%7Bp%7D%22),%0A++++++++++++None+=%3E+println!(%22has+no+value%22),%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/option/index.html#the-question-mark-operator-) The question mark operator, `?` ----------------------------------------------------------------------------------------------------------------------- Similar to the [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") type, when writing code that calls many functions that return the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") type, handling `Some`/`None` can be tedious. The question mark operator, [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , hides some of the boilerplate of propagating values up the call stack. It replaces this: fn add_last_numbers(stack: &mut Vec) -> Option { let a = stack.pop(); let b = stack.pop(); match (a, b) { (Some(x), Some(y)) => Some(x + y), _ => None, } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++fn+add_last_numbers(stack:+%26mut+Vec%3Ci32%3E)+-%3E+Option%3Ci32%3E+%7B%0A++++++++let+a+=+stack.pop();%0A++++++++let+b+=+stack.pop();%0A++++%0A++++++++match+(a,+b)+%7B%0A++++++++++++(Some(x),+Some(y))+=%3E+Some(x+%2B+y),%0A++++++++++++_+=%3E+None,%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") With this: fn add_last_numbers(stack: &mut Vec) -> Option { Some(stack.pop()? + stack.pop()?) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++fn+add_last_numbers(stack:+%26mut+Vec%3Ci32%3E)+-%3E+Option%3Ci32%3E+%7B%0A++++++++Some(stack.pop()?+%2B+stack.pop()?)%0A++++%7D%0A%7D&edition=2024 "Run code") _It’s much nicer!_ Ending the expression with [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") will result in the [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") ’s unwrapped value, unless the result is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") , in which case [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") is returned early from the enclosing function. [`?`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") can be used in functions that return [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") because of the early return of [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") that it provides. [§](https://doc.rust-lang.org/stable/std/option/index.html#representation) Representation ----------------------------------------------------------------------------------------- Rust guarantees to optimize the following types `T` such that [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") has the same size, alignment, and [function call ABI](https://doc.rust-lang.org/stable/std/primitive.fn.html#abi-compatibility) as `T`. It is therefore sound, when `T` is one of these types, to transmute a value `t` of type `T` to type `Option` (producing the value `Some(t)`) and to transmute a value `Some(t)` of type `Option` to type `T` (producing the value `t`). In some of these cases, Rust further guarantees the following: * `transmute::<_, Option>([0u8; size_of::()])` is sound and produces `Option::::None` * `transmute::<_, [u8; size_of::()]>(Option::::None)` is sound and produces `[0u8; size_of::()]` These cases are identified by the second column: | `T` | Transmuting between `[0u8; size_of::()]` and `Option::::None` sound? | | --- | --- | | [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html)
(specifically, only `Box`) | when `U: Sized` | | `&U` | when `U: Sized` | | `&mut U` | when `U: Sized` | | `fn`, `extern "C" fn`[1](https://doc.rust-lang.org/stable/std/option/index.html#fn1) | always | | [`num::NonZero*`](https://doc.rust-lang.org/stable/core/num/index.html "mod core::num") | always | | [`ptr::NonNull`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") | when `U: Sized` | | `#[repr(transparent)]` struct around one of the types in this list. | when it holds for the inner type | Under some conditions the above types `T` are also null pointer optimized when wrapped in a [`Result`](https://doc.rust-lang.org/stable/std/result/index.html#representation "mod std::result") . This is called the “null pointer optimization” or NPO. It is further guaranteed that, for the cases above, one can [`mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html "fn std::mem::transmute") from all valid values of `T` to `Option` and from `Some::(_)` to `T` (but transmuting `None::` to `T` is undefined behavior). [§](https://doc.rust-lang.org/stable/std/option/index.html#method-overview) Method overview ------------------------------------------------------------------------------------------- In addition to working with pattern matching, [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") provides a wide variety of different methods. ### [§](https://doc.rust-lang.org/stable/std/option/index.html#querying-the-variant) Querying the variant The [`is_some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.is_some "method std::option::Option::is_some") and [`is_none`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.is_none "method std::option::Option::is_none") methods return [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") or [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") , respectively. The [`is_some_and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.is_some_and "method std::option::Option::is_some_and") and [`is_none_or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.is_none_or "method std::option::Option::is_none_or") methods apply the provided function to the contents of the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") to produce a boolean value. If this is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") then a default result is returned instead without executing the function. ### [§](https://doc.rust-lang.org/stable/std/option/index.html#adapters-for-working-with-references) Adapters for working with references * [`as_ref`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_ref "method std::option::Option::as_ref") converts from `[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") ` to `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") T>` * [`as_mut`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_mut "method std::option::Option::as_mut") converts from `[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") ` to `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T>` * [`as_deref`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_deref "method std::option::Option::as_deref") converts from `[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") ` to `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") T::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "ops::Deref::Target") >` * [`as_deref_mut`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_deref_mut "method std::option::Option::as_deref_mut") converts from `[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") ` to `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "ops::Deref::Target") >` * [`as_pin_ref`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_pin_ref "method std::option::Option::as_pin_ref") converts from `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") >` to `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") T>>` * [`as_pin_mut`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_pin_mut "method std::option::Option::as_pin_mut") converts from `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") >` to `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T>>` * [`as_slice`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_slice "method std::option::Option::as_slice") returns a one-element slice of the contained value, if any. If this is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") , an empty slice is returned. * [`as_mut_slice`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.as_mut_slice "method std::option::Option::as_mut_slice") returns a mutable one-element slice of the contained value, if any. If this is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") , an empty slice is returned. ### [§](https://doc.rust-lang.org/stable/std/option/index.html#extracting-the-contained-value) Extracting the contained value These methods extract the contained value in an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") when it is the [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") variant. If the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") : * [`expect`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.expect "method std::option::Option::expect") panics with a provided custom message * [`unwrap`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap "method std::option::Option::unwrap") panics with a generic message * [`unwrap_or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_or "method std::option::Option::unwrap_or") returns the provided default value * [`unwrap_or_default`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_or_default "method std::option::Option::unwrap_or_default") returns the default value of the type `T` (which must implement the [`Default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") trait) * [`unwrap_or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_or_else "method std::option::Option::unwrap_or_else") returns the result of evaluating the provided function * [`unwrap_unchecked`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_unchecked "method std::option::Option::unwrap_unchecked") produces _[undefined behavior](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) _ ### [§](https://doc.rust-lang.org/stable/std/option/index.html#transforming-contained-values) Transforming contained values These methods transform [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") to [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") : * [`ok_or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.ok_or "method std::option::Option::ok_or") transforms [`Some(v)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") to [`Ok(v)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") , and [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") to [`Err(err)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") using the provided default `err` value * [`ok_or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.ok_or_else "method std::option::Option::ok_or_else") transforms [`Some(v)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") to [`Ok(v)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") , and [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") to a value of [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") using the provided function * [`transpose`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.transpose "method std::option::Option::transpose") transposes an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") of a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") into a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") These methods transform the [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") variant: * [`filter`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.filter "method std::option::Option::filter") calls the provided predicate function on the contained value `t` if the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`Some(t)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") , and returns [`Some(t)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") if the function returns `true`; otherwise, returns [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`flatten`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.flatten "method std::option::Option::flatten") removes one level of nesting from an [`Option>`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") * [`inspect`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.inspect "method std::option::Option::inspect") method takes ownership of the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") and applies the provided function to the contained value by reference if [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") * [`map`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map "method std::option::Option::map") transforms [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") to [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") by applying the provided function to the contained value of [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") and leaving [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") values unchanged These methods transform [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") to a value of a possibly different type `U`: * [`map_or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map_or "method std::option::Option::map_or") applies the provided function to the contained value of [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") , or returns the provided default value if the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`map_or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map_or_else "method std::option::Option::map_or_else") applies the provided function to the contained value of [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") , or returns the result of evaluating the provided fallback function if the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") These methods combine the [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") variants of two [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") values: * [`zip`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.zip "method std::option::Option::zip") returns [`Some((s, o))`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") if `self` is [`Some(s)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") and the provided [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") value is [`Some(o)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") ; otherwise, returns [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`zip_with`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.zip_with "method std::option::Option::zip_with") calls the provided function `f` and returns [`Some(f(s, o))`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") if `self` is [`Some(s)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") and the provided [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") value is [`Some(o)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") ; otherwise, returns [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") ### [§](https://doc.rust-lang.org/stable/std/option/index.html#boolean-operators) Boolean operators These methods treat the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") as a boolean value, where [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") acts like [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") and [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") acts like [`false`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") . There are two categories of these methods: ones that take an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") as input, and ones that take a function as input (to be lazily evaluated). The [`and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and "method std::option::Option::and") , [`or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or "method std::option::Option::or") , and [`xor`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.xor "method std::option::Option::xor") methods take another [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") as input, and produce an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") as output. Only the [`and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and "method std::option::Option::and") method can produce an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") value having a different inner type `U` than [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") . | method | self | input | output | | --- | --- | --- | --- | | [`and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and "method std::option::Option::and") | `None` | (ignored) | `None` | | [`and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and "method std::option::Option::and") | `Some(x)` | `None` | `None` | | [`and`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and "method std::option::Option::and") | `Some(x)` | `Some(y)` | `Some(y)` | | [`or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or "method std::option::Option::or") | `None` | `None` | `None` | | [`or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or "method std::option::Option::or") | `None` | `Some(y)` | `Some(y)` | | [`or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or "method std::option::Option::or") | `Some(x)` | (ignored) | `Some(x)` | | [`xor`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.xor "method std::option::Option::xor") | `None` | `None` | `None` | | [`xor`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.xor "method std::option::Option::xor") | `None` | `Some(y)` | `Some(y)` | | [`xor`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.xor "method std::option::Option::xor") | `Some(x)` | `None` | `Some(x)` | | [`xor`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.xor "method std::option::Option::xor") | `Some(x)` | `Some(y)` | `None` | The [`and_then`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and_then "method std::option::Option::and_then") and [`or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or_else "method std::option::Option::or_else") methods take a function as input, and only evaluate the function when they need to produce a new value. Only the [`and_then`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and_then "method std::option::Option::and_then") method can produce an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") value having a different inner type `U` than [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") . | method | self | function input | function result | output | | --- | --- | --- | --- | --- | | [`and_then`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and_then "method std::option::Option::and_then") | `None` | (not provided) | (not evaluated) | `None` | | [`and_then`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and_then "method std::option::Option::and_then") | `Some(x)` | `x` | `None` | `None` | | [`and_then`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and_then "method std::option::Option::and_then") | `Some(x)` | `x` | `Some(y)` | `Some(y)` | | [`or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or_else "method std::option::Option::or_else") | `None` | (not provided) | `None` | `None` | | [`or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or_else "method std::option::Option::or_else") | `None` | (not provided) | `Some(y)` | `Some(y)` | | [`or_else`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or_else "method std::option::Option::or_else") | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` | This is an example of using methods like [`and_then`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.and_then "method std::option::Option::and_then") and [`or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or "method std::option::Option::or") in a pipeline of method calls. Early stages of the pipeline pass failure values ([`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") ) through unchanged, and continue processing on success values ([`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") ). Toward the end, [`or`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.or "method std::option::Option::or") substitutes an error message if it receives [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") . let mut bt = BTreeMap::new(); bt.insert(20u8, "foo"); bt.insert(42u8, "bar"); let res = [0u8, 1, 11, 200, 22] .into_iter() .map(|x| { // `checked_sub()` returns `None` on error x.checked_sub(1) // same with `checked_mul()` .and_then(|x| x.checked_mul(2)) // `BTreeMap::get` returns `None` on error .and_then(|x| bt.get(&x)) // Substitute an error message if we have `None` so far .or(Some(&"error!")) .copied() // Won't panic because we unconditionally used `Some` above .unwrap() }) .collect::>(); assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BTreeMap;%0A++++let+mut+bt+=+BTreeMap::new();%0A++++bt.insert(20u8,+%22foo%22);%0A++++bt.insert(42u8,+%22bar%22);%0A++++let+res+=+%5B0u8,+1,+11,+200,+22%5D%0A++++++++.into_iter()%0A++++++++.map(%7Cx%7C+%7B%0A++++++++++++//+%60checked_sub()%60+returns+%60None%60+on+error%0A++++++++++++x.checked_sub(1)%0A++++++++++++++++//+same+with+%60checked_mul()%60%0A++++++++++++++++.and_then(%7Cx%7C+x.checked_mul(2))%0A++++++++++++++++//+%60BTreeMap::get%60+returns+%60None%60+on+error%0A++++++++++++++++.and_then(%7Cx%7C+bt.get(%26x))%0A++++++++++++++++//+Substitute+an+error+message+if+we+have+%60None%60+so+far%0A++++++++++++++++.or(Some(%26%22error!%22))%0A++++++++++++++++.copied()%0A++++++++++++++++//+Won%27t+panic+because+we+unconditionally+used+%60Some%60+above%0A++++++++++++++++.unwrap()%0A++++++++%7D)%0A++++++++.collect::%3CVec%3C_%3E%3E();%0A++++assert_eq!(res,+%5B%22error!%22,+%22error!%22,+%22foo%22,+%22error!%22,+%22bar%22%5D);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/option/index.html#comparison-operators) Comparison operators If `T` implements [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") then [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") will derive its [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") implementation. With this order, [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") compares as less than any [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") , and two [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") compare the same way as their contained values would in `T`. If `T` also implements [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , then so does [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") . assert!(None < Some(0)); assert!(Some(0) < Some(1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert!(None+%3C+Some(0));%0A++++assert!(Some(0)+%3C+Some(1));%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/option/index.html#iterating-over-option) Iterating over `Option` An [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") can be iterated over. This can be helpful if you need an iterator that is conditionally empty. The iterator will either produce a single value (when the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") ), or produce no values (when the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") ). For example, [`into_iter`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.into_iter "method std::option::Option::into_iter") acts like [`once(v)`](https://doc.rust-lang.org/stable/std/iter/fn.once.html "fn std::iter::once") if the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`Some(v)`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") , and like [`empty()`](https://doc.rust-lang.org/stable/std/iter/fn.empty.html "fn std::iter::empty") if the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") . Iterators over [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") come in three types: * [`into_iter`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.into_iter "method std::option::Option::into_iter") consumes the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") and produces the contained value * [`iter`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.iter "method std::option::Option::iter") produces an immutable reference of type `&T` to the contained value * [`iter_mut`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.iter_mut "method std::option::Option::iter_mut") produces a mutable reference of type `&mut T` to the contained value An iterator over [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") can be useful when chaining iterators, for example, to conditionally insert items. (It’s not always necessary to explicitly call an iterator constructor: many [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") methods that accept other iterators will also accept iterable types that implement [`IntoIterator`](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , which includes [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") .) let yep = Some(42); let nope = None; // chain() already calls into_iter(), so we don't have to do so let nums: Vec = (0..4).chain(yep).chain(4..8).collect(); assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]); let nums: Vec = (0..4).chain(nope).chain(4..8).collect(); assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+yep+=+Some(42);%0A++++let+nope+=+None;%0A++++//+chain()+already+calls+into_iter(),+so+we+don%27t+have+to+do+so%0A++++let+nums:+Vec%3Ci32%3E+=+(0..4).chain(yep).chain(4..8).collect();%0A++++assert_eq!(nums,+%5B0,+1,+2,+3,+42,+4,+5,+6,+7%5D);%0A++++let+nums:+Vec%3Ci32%3E+=+(0..4).chain(nope).chain(4..8).collect();%0A++++assert_eq!(nums,+%5B0,+1,+2,+3,+4,+5,+6,+7%5D);%0A%7D&edition=2024 "Run code") One reason to chain iterators in this way is that a function returning `impl Iterator` must have all possible return values be of the same concrete type. Chaining an iterated [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") can help with that. fn make_iter(do_insert: bool) -> impl Iterator { // Explicit returns to illustrate return types matching match do_insert { true => return (0..4).chain(Some(42)).chain(4..8), false => return (0..4).chain(None).chain(4..8), } } println!("{:?}", make_iter(true).collect::>()); println!("{:?}", make_iter(false).collect::>()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+make_iter(do_insert:+bool)+-%3E+impl+Iterator%3CItem+=+i32%3E+%7B%0A++++++++//+Explicit+returns+to+illustrate+return+types+matching%0A++++++++match+do_insert+%7B%0A++++++++++++true+=%3E+return+(0..4).chain(Some(42)).chain(4..8),%0A++++++++++++false+=%3E+return+(0..4).chain(None).chain(4..8),%0A++++++++%7D%0A++++%7D%0A++++println!(%22%7B:?%7D%22,+make_iter(true).collect::%3CVec%3C_%3E%3E());%0A++++println!(%22%7B:?%7D%22,+make_iter(false).collect::%3CVec%3C_%3E%3E());%0A%7D&edition=2024 "Run code") If we try to do the same thing, but using [`once()`](https://doc.rust-lang.org/stable/std/iter/fn.once.html "fn std::iter::once") and [`empty()`](https://doc.rust-lang.org/stable/std/iter/fn.empty.html "fn std::iter::empty") , we can’t return `impl Iterator` anymore because the concrete types of the return values differ. [ⓘ](https://doc.rust-lang.org/stable/std/option/index.html# "This example deliberately fails to compile") // This won't compile because all possible returns from the function // must have the same concrete type. fn make_iter(do_insert: bool) -> impl Iterator { // Explicit returns to illustrate return types not matching match do_insert { true => return (0..4).chain(once(42)).chain(4..8), false => return (0..4).chain(empty()).chain(4..8), } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::iter::%7Bempty,+once%7D;%0A++++//+This+won%27t+compile+because+all+possible+returns+from+the+function%0A++++//+must+have+the+same+concrete+type.%0A++++fn+make_iter(do_insert:+bool)+-%3E+impl+Iterator%3CItem+=+i32%3E+%7B%0A++++++++//+Explicit+returns+to+illustrate+return+types+not+matching%0A++++++++match+do_insert+%7B%0A++++++++++++true+=%3E+return+(0..4).chain(once(42)).chain(4..8),%0A++++++++++++false+=%3E+return+(0..4).chain(empty()).chain(4..8),%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/option/index.html#collecting-into-option) Collecting into `Option` [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") implements the [`FromIterator`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E "enum std::option::Option") trait, which allows an iterator over [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") values to be collected into an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") of a collection of each contained value of the original [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") values, or [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if any of the elements was [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") . let v = [Some(2), Some(4), None, Some(8)]; let res: Option> = v.into_iter().collect(); assert_eq!(res, None); let v = [Some(2), Some(4), Some(8)]; let res: Option> = v.into_iter().collect(); assert_eq!(res, Some(vec![2, 4, 8])); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v+=+%5BSome(2),+Some(4),+None,+Some(8)%5D;%0A++++let+res:+Option%3CVec%3C_%3E%3E+=+v.into_iter().collect();%0A++++assert_eq!(res,+None);%0A++++let+v+=+%5BSome(2),+Some(4),+Some(8)%5D;%0A++++let+res:+Option%3CVec%3C_%3E%3E+=+v.into_iter().collect();%0A++++assert_eq!(res,+Some(vec!%5B2,+4,+8%5D));%0A%7D&edition=2024 "Run code") [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") also implements the [`Product`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E "enum std::option::Option") and [`Sum`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E "enum std::option::Option") traits, allowing an iterator over [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") values to provide the [`product`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.product "method std::iter::Iterator::product") and [`sum`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.sum "method std::iter::Iterator::sum") methods. let v = [None, Some(1), Some(2), Some(3)]; let res: Option = v.into_iter().sum(); assert_eq!(res, None); let v = [Some(1), Some(2), Some(21)]; let res: Option = v.into_iter().product(); assert_eq!(res, Some(42)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v+=+%5BNone,+Some(1),+Some(2),+Some(3)%5D;%0A++++let+res:+Option%3Ci32%3E+=+v.into_iter().sum();%0A++++assert_eq!(res,+None);%0A++++let+v+=+%5BSome(1),+Some(2),+Some(21)%5D;%0A++++let+res:+Option%3Ci32%3E+=+v.into_iter().product();%0A++++assert_eq!(res,+Some(42));%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/option/index.html#modifying-an-option-in-place) Modifying an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") in-place These methods return a mutable reference to the contained value of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") : * [`insert`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.insert "method std::option::Option::insert") inserts a value, dropping any old contents * [`get_or_insert`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.get_or_insert "method std::option::Option::get_or_insert") gets the current value, inserting a provided default value if it is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`get_or_insert_default`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.get_or_insert_default "method std::option::Option::get_or_insert_default") gets the current value, inserting the default value of type `T` (which must implement [`Default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") ) if it is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`get_or_insert_with`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.get_or_insert_with "method std::option::Option::get_or_insert_with") gets the current value, inserting a default computed by the provided function if it is [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") These methods transfer ownership of the contained value of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") : * [`take`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.take "method std::option::Option::take") takes ownership of the contained value of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , if any, replacing the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") with [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") * [`replace`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.replace "method std::option::Option::replace") takes ownership of the contained value of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , if any, replacing the [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") with a [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") containing the provided value [§](https://doc.rust-lang.org/stable/std/option/index.html#examples) Examples ----------------------------------------------------------------------------- Basic pattern matching on [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") : let msg = Some("howdy"); // Take a reference to the contained string if let Some(m) = &msg { println!("{}", *m); } // Remove the contained string, destroying the Option let unwrapped_msg = msg.unwrap_or("default message"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+msg+=+Some(%22howdy%22);%0A++++%0A++++//+Take+a+reference+to+the+contained+string%0A++++if+let+Some(m)+=+%26msg+%7B%0A++++++++println!(%22%7B%7D%22,+*m);%0A++++%7D%0A++++%0A++++//+Remove+the+contained+string,+destroying+the+Option%0A++++let+unwrapped_msg+=+msg.unwrap_or(%22default+message%22);%0A%7D&edition=2024 "Run code") Initialize a result to [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") before a loop: enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) } // A list of data to search through. let all_the_big_things = [\ Kingdom::Plant(250, "redwood"),\ Kingdom::Plant(230, "noble fir"),\ Kingdom::Plant(229, "sugar pine"),\ Kingdom::Animal(25, "blue whale"),\ Kingdom::Animal(19, "fin whale"),\ Kingdom::Animal(15, "north pacific right whale"),\ ]; // We're going to search for the name of the biggest animal, // but to start with we've just got `None`. let mut name_of_biggest_animal = None; let mut size_of_biggest_animal = 0; for big_thing in &all_the_big_things { match *big_thing { Kingdom::Animal(size, name) if size > size_of_biggest_animal => { // Now we've found the name of some big animal size_of_biggest_animal = size; name_of_biggest_animal = Some(name); } Kingdom::Animal(..) | Kingdom::Plant(..) => () } } match name_of_biggest_animal { Some(name) => println!("the biggest animal is {name}"), None => println!("there are no animals :("), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+Kingdom+%7B+Plant(u32,+%26%27static+str),+Animal(u32,+%26%27static+str)+%7D%0A++++%0A++++//+A+list+of+data+to+search+through.%0A++++let+all_the_big_things+=+%5B%0A++++++++Kingdom::Plant(250,+%22redwood%22),%0A++++++++Kingdom::Plant(230,+%22noble+fir%22),%0A++++++++Kingdom::Plant(229,+%22sugar+pine%22),%0A++++++++Kingdom::Animal(25,+%22blue+whale%22),%0A++++++++Kingdom::Animal(19,+%22fin+whale%22),%0A++++++++Kingdom::Animal(15,+%22north+pacific+right+whale%22),%0A++++%5D;%0A++++%0A++++//+We%27re+going+to+search+for+the+name+of+the+biggest+animal,%0A++++//+but+to+start+with+we%27ve+just+got+%60None%60.%0A++++let+mut+name_of_biggest_animal+=+None;%0A++++let+mut+size_of_biggest_animal+=+0;%0A++++for+big_thing+in+%26all_the_big_things+%7B%0A++++++++match+*big_thing+%7B%0A++++++++++++Kingdom::Animal(size,+name)+if+size+%3E+size_of_biggest_animal+=%3E+%7B%0A++++++++++++++++//+Now+we%27ve+found+the+name+of+some+big+animal%0A++++++++++++++++size_of_biggest_animal+=+size;%0A++++++++++++++++name_of_biggest_animal+=+Some(name);%0A++++++++++++%7D%0A++++++++++++Kingdom::Animal(..)+%7C+Kingdom::Plant(..)+=%3E+()%0A++++++++%7D%0A++++%7D%0A++++%0A++++match+name_of_biggest_animal+%7B%0A++++++++Some(name)+=%3E+println!(%22the+biggest+animal+is+%7Bname%7D%22),%0A++++++++None+=%3E+println!(%22there+are+no+animals+:(%22),%0A++++%7D%0A%7D&edition=2024 "Run code") * * * 1. this remains true for `unsafe` variants, any argument/return types, and any other ABI: `[unsafe] extern "abi" fn` (_e.g._, `extern "system" fn`) [↩](https://doc.rust-lang.org/stable/std/option/index.html#fnref1) Structs[§](https://doc.rust-lang.org/stable/std/option/index.html#structs) --------------------------------------------------------------------------- [IntoIter](https://doc.rust-lang.org/stable/std/option/struct.IntoIter.html "struct std::option::IntoIter") An iterator over the value in [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") variant of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") . [Iter](https://doc.rust-lang.org/stable/std/option/struct.Iter.html "struct std::option::Iter") An iterator over a reference to the [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") variant of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") . [IterMut](https://doc.rust-lang.org/stable/std/option/struct.IterMut.html "struct std::option::IterMut") An iterator over a mutable reference to the [`Some`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") variant of an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") . Enums[§](https://doc.rust-lang.org/stable/std/option/index.html#enums) ----------------------------------------------------------------------- [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") The `Option` type. See [the module level documentation](https://doc.rust-lang.org/stable/std/option/index.html "mod std::option") for more. --- # std::net - Rust [Module net](https://doc.rust-lang.org/stable/std/net/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module net Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#1-72) Expand description Networking primitives for TCP/UDP communication. This module provides networking functionality for the Transmission Control and User Datagram Protocols, as well as types for IP and socket addresses and functions related to network properties. [§](https://doc.rust-lang.org/stable/std/net/index.html#organization) Organization ---------------------------------------------------------------------------------- * [`TcpListener`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html "struct std::net::TcpListener") and [`TcpStream`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") provide functionality for communication over TCP * [`UdpSocket`](https://doc.rust-lang.org/stable/std/net/struct.UdpSocket.html "struct std::net::UdpSocket") provides functionality for communication over UDP * [`IpAddr`](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") represents IP addresses of either IPv4 or IPv6; [`Ipv4Addr`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") and [`Ipv6Addr`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") are respectively IPv4 and IPv6 addresses * [`SocketAddr`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html "enum std::net::SocketAddr") represents socket addresses of either IPv4 or IPv6; [`SocketAddrV4`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html "struct std::net::SocketAddrV4") and [`SocketAddrV6`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html "struct std::net::SocketAddrV6") are respectively IPv4 and IPv6 socket addresses * [`ToSocketAddrs`](https://doc.rust-lang.org/stable/std/net/trait.ToSocketAddrs.html "trait std::net::ToSocketAddrs") is a trait that is used for generic address resolution when interacting with networking objects like [`TcpListener`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html "struct std::net::TcpListener") , [`TcpStream`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") or [`UdpSocket`](https://doc.rust-lang.org/stable/std/net/struct.UdpSocket.html "struct std::net::UdpSocket") * Other types are return or parameter types for various methods in this module Rust disables inheritance of socket objects to child processes by default when possible. For example, through the use of the `CLOEXEC` flag in UNIX systems or the `HANDLE_FLAG_INHERIT` flag on Windows. Structs[§](https://doc.rust-lang.org/stable/std/net/index.html#structs) ------------------------------------------------------------------------ [AddrParseError](https://doc.rust-lang.org/stable/std/net/struct.AddrParseError.html "struct std::net::AddrParseError") An error which can be returned when parsing an IP address or a socket address. [Incoming](https://doc.rust-lang.org/stable/std/net/struct.Incoming.html "struct std::net::Incoming") An iterator that infinitely [`accept`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.accept "method std::net::TcpListener::accept") s connections on a [`TcpListener`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html "struct std::net::TcpListener") . [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") An IPv4 address. [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") An IPv6 address. [SocketAddrV4](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html "struct std::net::SocketAddrV4") An IPv4 socket address. [SocketAddrV6](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html "struct std::net::SocketAddrV6") An IPv6 socket address. [TcpListener](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html "struct std::net::TcpListener") A TCP socket server, listening for connections. [TcpStream](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") A TCP stream between a local and a remote socket. [UdpSocket](https://doc.rust-lang.org/stable/std/net/struct.UdpSocket.html "struct std::net::UdpSocket") A UDP socket. [IntoIncoming](https://doc.rust-lang.org/stable/std/net/struct.IntoIncoming.html "struct std::net::IntoIncoming") Experimental An iterator that infinitely [`accept`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.accept "method std::net::TcpListener::accept") s connections on a [`TcpListener`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html "struct std::net::TcpListener") . Enums[§](https://doc.rust-lang.org/stable/std/net/index.html#enums) -------------------------------------------------------------------- [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") An IP address, either IPv4 or IPv6. [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") Possible values which can be passed to the [`TcpStream::shutdown`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.shutdown "method std::net::TcpStream::shutdown") method. [SocketAddr](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html "enum std::net::SocketAddr") An internet socket address, either IPv4 or IPv6. [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") Experimental Scope of an [IPv6 multicast address](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") as defined in [IETF RFC 7346 section 2](https://tools.ietf.org/html/rfc7346#section-2) . Traits[§](https://doc.rust-lang.org/stable/std/net/index.html#traits) ---------------------------------------------------------------------- [ToSocketAddrs](https://doc.rust-lang.org/stable/std/net/trait.ToSocketAddrs.html "trait std::net::ToSocketAddrs") A trait for objects which can be converted or resolved to one or more [`SocketAddr`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html "enum std::net::SocketAddr") values. Functions[§](https://doc.rust-lang.org/stable/std/net/index.html#functions) ---------------------------------------------------------------------------- [hostname](https://doc.rust-lang.org/stable/std/net/fn.hostname.html "fn std::net::hostname") Experimental Returns the system hostname. --- # std::sync::mpmc - Rust [Module mpmc](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#) -------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) Module mpmc Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/sync/mpmc/mod.rs.html#1-1387) 🔬This is a nightly-only experimental API. (`mpmc_channel` [#126840](https://github.com/rust-lang/rust/issues/126840) ) Expand description Multi-producer, multi-consumer FIFO queue communication primitives. This module provides message-based communication over channels, concretely defined by two types: * [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Sender.html "struct std::sync::mpmc::Sender") * [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Sender.html "struct std::sync::mpmc::Sender") s are used to send data to a set of [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") s. Both sender and receiver are cloneable (multi-producer) such that many threads can send simultaneously to receivers (multi-consumer). These channels come in two flavors: 1. An asynchronous, infinitely buffered channel. The [`channel`](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.channel.html "fn std::sync::mpmc::channel") function will return a `(Sender, Receiver)` tuple where all sends will be **asynchronous** (they never block). The channel conceptually has an infinite buffer. 2. A synchronous, bounded channel. The [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.sync_channel.html "fn std::sync::mpmc::sync_channel") function will return a `(Sender, Receiver)` tuple where the storage for pending messages is a pre-allocated buffer of a fixed size. All sends will be **synchronous** by blocking until there is buffer space available. Note that a bound of 0 is allowed, causing the channel to become a “rendezvous” channel where each sender atomically hands off a message to a receiver. ### [§](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#disconnection) Disconnection The send and receive operations on channels will all return a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") indicating whether the operation succeeded or not. An unsuccessful operation is normally indicative of the other half of a channel having “hung up” by being dropped in its corresponding thread. Once half of a channel has been deallocated, most operations can no longer continue to make progress, so [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") will be returned. Many applications will continue to [`unwrap`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap "method std::result::Result::unwrap") the results returned from this module, instigating a propagation of failure among threads if one unexpectedly dies. [§](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#examples) Examples -------------------------------------------------------------------------------- Simple usage: #![feature(mpmc_channel)] use std::thread; use std::sync::mpmc::channel; // Create a simple streaming channel let (tx, rx) = channel(); thread::spawn(move || { tx.send(10).unwrap(); }); assert_eq!(rx.recv().unwrap(), 10); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(mpmc_channel)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::sync::mpmc::channel;%0A++++%0A++++//+Create+a+simple+streaming+channel%0A++++let+(tx,+rx)+=+channel();%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++tx.send(10).unwrap();%0A++++%7D);%0A++++assert_eq!(rx.recv().unwrap(),+10);%0A%7D&version=nightly&edition=2024 "Run code") Shared usage: #![feature(mpmc_channel)] use std::thread; use std::sync::mpmc::channel; thread::scope(|s| { // Create a shared channel that can be sent along from many threads // where tx is the sending half (tx for transmission), and rx is the receiving // half (rx for receiving). let (tx, rx) = channel(); for i in 0..10 { let tx = tx.clone(); s.spawn(move || { tx.send(i).unwrap(); }); } for _ in 0..5 { let rx1 = rx.clone(); let rx2 = rx.clone(); s.spawn(move || { let j = rx1.recv().unwrap(); assert!(0 <= j && j < 10); }); s.spawn(move || { let j = rx2.recv().unwrap(); assert!(0 <= j && j < 10); }); } }) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(mpmc_channel)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::sync::mpmc::channel;%0A++++%0A++++thread::scope(%7Cs%7C+%7B%0A++++++++//+Create+a+shared+channel+that+can+be+sent+along+from+many+threads%0A++++++++//+where+tx+is+the+sending+half+(tx+for+transmission),+and+rx+is+the+receiving%0A++++++++//+half+(rx+for+receiving).%0A++++++++let+(tx,+rx)+=+channel();%0A++++++++for+i+in+0..10+%7B%0A++++++++++++let+tx+=+tx.clone();%0A++++++++++++s.spawn(move+%7C%7C+%7B%0A++++++++++++++++tx.send(i).unwrap();%0A++++++++++++%7D);%0A++++++++%7D%0A++++%0A++++++++for+_+in+0..5+%7B%0A++++++++++++let+rx1+=+rx.clone();%0A++++++++++++let+rx2+=+rx.clone();%0A++++++++++++s.spawn(move+%7C%7C+%7B%0A++++++++++++++++let+j+=+rx1.recv().unwrap();%0A++++++++++++++++assert!(0+%3C=+j+%26%26+j+%3C+10);%0A++++++++++++%7D);%0A++++++++++++s.spawn(move+%7C%7C+%7B%0A++++++++++++++++let+j+=+rx2.recv().unwrap();%0A++++++++++++++++assert!(0+%3C=+j+%26%26+j+%3C+10);%0A++++++++++++%7D);%0A++++++++%7D%0A++++%7D)%0A%7D&version=nightly&edition=2024 "Run code") Propagating panics: #![feature(mpmc_channel)] use std::sync::mpmc::channel; // The call to recv() will return an error because the channel has already // hung up (or been deallocated) let (tx, rx) = channel::(); drop(tx); assert!(rx.recv().is_err()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(mpmc_channel)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::sync::mpmc::channel;%0A++++%0A++++//+The+call+to+recv()+will+return+an+error+because+the+channel+has+already%0A++++//+hung+up+(or+been+deallocated)%0A++++let+(tx,+rx)+=+channel::%3Ci32%3E();%0A++++drop(tx);%0A++++assert!(rx.recv().is_err());%0A%7D&version=nightly&edition=2024 "Run code") Re-exports[§](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#reexports) ----------------------------------------------------------------------------------- `pub use crate::sync::mpsc::[RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") ;` `pub use crate::sync::mpsc::[RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") ;` `pub use crate::sync::mpsc::[SendError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SendError.html "struct std::sync::mpsc::SendError") ;` `pub use crate::sync::mpsc::[TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") ;` `pub use crate::sync::mpsc::[TrySendError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TrySendError.html "enum std::sync::mpsc::TrySendError") ;` Structs[§](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#structs) ------------------------------------------------------------------------------ [IntoIter](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.IntoIter.html "struct std::sync::mpmc::IntoIter") Experimental An owning iterator over messages on a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") , created by [`into_iter`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html#method.into_iter "method std::sync::mpmc::Receiver::into_iter") . [Iter](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Iter.html "struct std::sync::mpmc::Iter") Experimental An iterator over messages on a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") , created by [`iter`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html#method.iter "method std::sync::mpmc::Receiver::iter") . [Receiver](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") Experimental The receiving half of Rust’s [`channel`](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.channel.html "fn std::sync::mpmc::channel") (or [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.sync_channel.html "fn std::sync::mpmc::sync_channel") ) type. Different threads can share this [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") by cloning it. [Sender](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Sender.html "struct std::sync::mpmc::Sender") Experimental The sending-half of Rust’s synchronous [`channel`](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.channel.html "fn std::sync::mpmc::channel") type. [TryIter](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.TryIter.html "struct std::sync::mpmc::TryIter") Experimental An iterator that attempts to yield all pending values for a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html "struct std::sync::mpmc::Receiver") , created by [`try_iter`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Receiver.html#method.try_iter "method std::sync::mpmc::Receiver::try_iter") . Enums[§](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#enums) -------------------------------------------------------------------------- [SendTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpmc/enum.SendTimeoutError.html "enum std::sync::mpmc::SendTimeoutError") Experimental An error returned from the [`send_timeout`](https://doc.rust-lang.org/stable/std/sync/mpmc/struct.Sender.html#method.send_timeout "method std::sync::mpmc::Sender::send_timeout") method. Functions[§](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html#functions) ---------------------------------------------------------------------------------- [channel](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.channel.html "fn std::sync::mpmc::channel") Experimental Creates a new asynchronous channel, returning the sender/receiver halves. [sync\_channel](https://doc.rust-lang.org/stable/std/sync/mpmc/fn.sync_channel.html "fn std::sync::mpmc::sync_channel") Experimental Creates a new synchronous, bounded channel. --- # std::array - Rust [Module array](https://doc.rust-lang.org/stable/std/array/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module array Copy item path =========================== 1.35.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#302) Expand description Utilities for the array primitive type. _[See also the array primitive type](https://doc.rust-lang.org/stable/std/primitive.array.html "primitive array") ._ Structs[§](https://doc.rust-lang.org/stable/std/array/index.html#structs) -------------------------------------------------------------------------- [IntoIter](https://doc.rust-lang.org/stable/std/array/struct.IntoIter.html "struct std::array::IntoIter") A by-value [array](https://doc.rust-lang.org/stable/std/primitive.array.html "primitive array") iterator. [TryFromSliceError](https://doc.rust-lang.org/stable/std/array/struct.TryFromSliceError.html "struct std::array::TryFromSliceError") The error type returned when a conversion from a slice to an array fails. Functions[§](https://doc.rust-lang.org/stable/std/array/index.html#functions) ------------------------------------------------------------------------------ [from\_fn](https://doc.rust-lang.org/stable/std/array/fn.from_fn.html "fn std::array::from_fn") Creates an array where each element is produced by calling `f` with that element’s index while walking forward through the array. [from\_mut](https://doc.rust-lang.org/stable/std/array/fn.from_mut.html "fn std::array::from_mut") Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying). [from\_ref](https://doc.rust-lang.org/stable/std/array/fn.from_ref.html "fn std::array::from_ref") Converts a reference to `T` into a reference to an array of length 1 (without copying). [repeat](https://doc.rust-lang.org/stable/std/array/fn.repeat.html "fn std::array::repeat") Creates an array of type `[T; N]` by repeatedly cloning a value. [try\_from\_fn](https://doc.rust-lang.org/stable/std/array/fn.try_from_fn.html "fn std::array::try_from_fn") Experimental Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call. Unlike [`from_fn`](https://doc.rust-lang.org/stable/std/array/fn.from_fn.html "fn std::array::from_fn") , where the element creation can’t fail, this version will return an error if any element creation was unsuccessful. --- # std::assert_matches - Rust [Module assert\_matches](https://doc.rust-lang.org/stable/std/assert_matches/index.html#) ------------------------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Module assert\_matches Copy item path ===================================== [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#227) 🔬This is a nightly-only experimental API. (`assert_matches` [#82775](https://github.com/rust-lang/rust/issues/82775) ) Expand description Unstable module containing the unstable `assert_matches` macro. Macros[§](https://doc.rust-lang.org/stable/std/assert_matches/index.html#macros) --------------------------------------------------------------------------------- [assert\_matches](https://doc.rust-lang.org/stable/std/assert_matches/macro.assert_matches.html "macro std::assert_matches::assert_matches") Experimental Asserts that an expression matches the provided pattern. [debug\_assert\_matches](https://doc.rust-lang.org/stable/std/assert_matches/macro.debug_assert_matches.html "macro std::assert_matches::debug_assert_matches") Experimental Asserts that an expression matches the provided pattern. --- # std::from - Rust [Module from](https://doc.rust-lang.org/stable/std/from/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module from Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/lib.rs.html#736) 🔬This is a nightly-only experimental API. (`derive_from` [#144889](https://github.com/rust-lang/rust/issues/144889) ) Expand description Unstable module containing the unstable `From` derive macro. Derive Macros[§](https://doc.rust-lang.org/stable/std/from/index.html#derives) ------------------------------------------------------------------------------- [From](https://doc.rust-lang.org/stable/std/from/derive.From.html "derive std::from::From") Experimental Derive macro generating an impl of the trait `From`. Currently, it can only be used on single-field structs. --- # cfg in std - Rust [cfg](https://doc.rust-lang.org/stable/std/macro.cfg.html#) ------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro cfg Copy item path ======================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1417) macro_rules! cfg { ($($cfg:tt)*) => { ... }; } Expand description Evaluates boolean combinations of configuration flags at compile-time. In addition to the `#[cfg]` attribute, this macro is provided to allow boolean expression evaluation of configuration flags. This frequently leads to less duplicated code. The syntax given to this macro is the same syntax as the [`cfg`](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#the-cfg-attribute) attribute. `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For example, all blocks in an if/else expression need to be valid when `cfg!` is used for the condition, regardless of what `cfg!` is evaluating. [§](https://doc.rust-lang.org/stable/std/macro.cfg.html#examples) Examples -------------------------------------------------------------------------- let my_directory = if cfg!(windows) { "windows-specific-directory" } else { "unix-directory" }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+my_directory+=+if+cfg!(windows)+%7B%0A++++++++%22windows-specific-directory%22%0A++++%7D+else+%7B%0A++++++++%22unix-directory%22%0A++++%7D;%0A%7D&edition=2024 "Run code") --- # std::sync::mpsc - Rust [Module mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html#) -------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) Module mpsc Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1-1212) Expand description Multi-producer, single-consumer FIFO queue communication primitives. This module provides message-based communication over channels, concretely defined among three types: * [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") * [`SyncSender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html "struct std::sync::mpsc::SyncSender") * [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") A [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") or [`SyncSender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html "struct std::sync::mpsc::SyncSender") is used to send data to a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") . Both senders are clone-able (multi-producer) such that many threads can send simultaneously to one receiver (single-consumer). These channels come in two flavors: 1. An asynchronous, infinitely buffered channel. The [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") function will return a `(Sender, Receiver)` tuple where all sends will be **asynchronous** (they never block). The channel conceptually has an infinite buffer. 2. A synchronous, bounded channel. The [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") function will return a `(SyncSender, Receiver)` tuple where the storage for pending messages is a pre-allocated buffer of a fixed size. All sends will be **synchronous** by blocking until there is buffer space available. Note that a bound of 0 is allowed, causing the channel to become a “rendezvous” channel where each sender atomically hands off a message to a receiver. ### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html#disconnection) Disconnection The send and receive operations on channels will all return a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") indicating whether the operation succeeded or not. An unsuccessful operation is normally indicative of the other half of a channel having “hung up” by being dropped in its corresponding thread. Once half of a channel has been deallocated, most operations can no longer continue to make progress, so [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") will be returned. Many applications will continue to [`unwrap`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap "method std::result::Result::unwrap") the results returned from this module, instigating a propagation of failure among threads if one unexpectedly dies. [§](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html#examples) Examples -------------------------------------------------------------------------------- Simple usage: use std::thread; use std::sync::mpsc::channel; // Create a simple streaming channel let (tx, rx) = channel(); thread::spawn(move || { tx.send(10).unwrap(); }); assert_eq!(rx.recv().unwrap(), 10); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::sync::mpsc::channel;%0A++++%0A++++//+Create+a+simple+streaming+channel%0A++++let+(tx,+rx)+=+channel();%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++tx.send(10).unwrap();%0A++++%7D);%0A++++assert_eq!(rx.recv().unwrap(),+10);%0A%7D&edition=2024 "Run code") Shared usage: use std::thread; use std::sync::mpsc::channel; // Create a shared channel that can be sent along from many threads // where tx is the sending half (tx for transmission), and rx is the receiving // half (rx for receiving). let (tx, rx) = channel(); for i in 0..10 { let tx = tx.clone(); thread::spawn(move || { tx.send(i).unwrap(); }); } for _ in 0..10 { let j = rx.recv().unwrap(); assert!(0 <= j && j < 10); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::sync::mpsc::channel;%0A++++%0A++++//+Create+a+shared+channel+that+can+be+sent+along+from+many+threads%0A++++//+where+tx+is+the+sending+half+(tx+for+transmission),+and+rx+is+the+receiving%0A++++//+half+(rx+for+receiving).%0A++++let+(tx,+rx)+=+channel();%0A++++for+i+in+0..10+%7B%0A++++++++let+tx+=+tx.clone();%0A++++++++thread::spawn(move+%7C%7C+%7B%0A++++++++++++tx.send(i).unwrap();%0A++++++++%7D);%0A++++%7D%0A++++%0A++++for+_+in+0..10+%7B%0A++++++++let+j+=+rx.recv().unwrap();%0A++++++++assert!(0+%3C=+j+%26%26+j+%3C+10);%0A++++%7D%0A%7D&edition=2024 "Run code") Propagating panics: use std::sync::mpsc::channel; // The call to recv() will return an error because the channel has already // hung up (or been deallocated) let (tx, rx) = channel::(); drop(tx); assert!(rx.recv().is_err()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc::channel;%0A++++%0A++++//+The+call+to+recv()+will+return+an+error+because+the+channel+has+already%0A++++//+hung+up+(or+been+deallocated)%0A++++let+(tx,+rx)+=+channel::%3Ci32%3E();%0A++++drop(tx);%0A++++assert!(rx.recv().is_err());%0A%7D&edition=2024 "Run code") Synchronous channels: use std::thread; use std::sync::mpsc::sync_channel; let (tx, rx) = sync_channel::(0); thread::spawn(move || { // This will wait for the parent thread to start receiving tx.send(53).unwrap(); }); rx.recv().unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::sync::mpsc::sync_channel;%0A++++%0A++++let+(tx,+rx)+=+sync_channel::%3Ci32%3E(0);%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++//+This+will+wait+for+the+parent+thread+to+start+receiving%0A++++++++tx.send(53).unwrap();%0A++++%7D);%0A++++rx.recv().unwrap();%0A%7D&edition=2024 "Run code") Unbounded receive loop: use std::sync::mpsc::sync_channel; use std::thread; let (tx, rx) = sync_channel(3); for _ in 0..3 { // It would be the same without thread and clone here // since there will still be one `tx` left. let tx = tx.clone(); // cloned tx dropped within thread thread::spawn(move || tx.send("ok").unwrap()); } // Drop the last sender to stop `rx` waiting for message. // The program will not complete if we comment this out. // **All** `tx` needs to be dropped for `rx` to have `Err`. drop(tx); // Unbounded receiver waiting for all senders to complete. while let Ok(msg) = rx.recv() { println!("{msg}"); } println!("completed"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc::sync_channel;%0A++++use+std::thread;%0A++++%0A++++let+(tx,+rx)+=+sync_channel(3);%0A++++%0A++++for+_+in+0..3+%7B%0A++++++++//+It+would+be+the+same+without+thread+and+clone+here%0A++++++++//+since+there+will+still+be+one+%60tx%60+left.%0A++++++++let+tx+=+tx.clone();%0A++++++++//+cloned+tx+dropped+within+thread%0A++++++++thread::spawn(move+%7C%7C+tx.send(%22ok%22).unwrap());%0A++++%7D%0A++++%0A++++//+Drop+the+last+sender+to+stop+%60rx%60+waiting+for+message.%0A++++//+The+program+will+not+complete+if+we+comment+this+out.%0A++++//+**All**+%60tx%60+needs+to+be+dropped+for+%60rx%60+to+have+%60Err%60.%0A++++drop(tx);%0A++++%0A++++//+Unbounded+receiver+waiting+for+all+senders+to+complete.%0A++++while+let+Ok(msg)+=+rx.recv()+%7B%0A++++++++println!(%22%7Bmsg%7D%22);%0A++++%7D%0A++++%0A++++println!(%22completed%22);%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html#structs) ------------------------------------------------------------------------------ [IntoIter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.IntoIter.html "struct std::sync::mpsc::IntoIter") An owning iterator over messages on a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") , created by [`into_iter`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.into_iter "method std::sync::mpsc::Receiver::into_iter") . [Iter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Iter.html "struct std::sync::mpsc::Iter") An iterator over messages on a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") , created by [`iter`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.iter "method std::sync::mpsc::Receiver::iter") . [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") The receiving half of Rust’s [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") (or [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") ) type. This half can only be owned by one thread. [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") An error returned from the [`recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv "method std::sync::mpsc::Receiver::recv") function on a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") . [SendError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SendError.html "struct std::sync::mpsc::SendError") An error returned from the [`Sender::send`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html#method.send "method std::sync::mpsc::Sender::send") or [`SyncSender::send`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html#method.send "method std::sync::mpsc::SyncSender::send") function on **channel**s. [Sender](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") The sending-half of Rust’s asynchronous [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") type. [SyncSender](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html "struct std::sync::mpsc::SyncSender") The sending-half of Rust’s synchronous [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") type. [TryIter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.TryIter.html "struct std::sync::mpsc::TryIter") An iterator that attempts to yield all pending values for a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") , created by [`try_iter`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_iter "method std::sync::mpsc::Receiver::try_iter") . Enums[§](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html#enums) -------------------------------------------------------------------------- [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") This enumeration is the list of possible errors that made [`recv_timeout`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv_timeout "method std::sync::mpsc::Receiver::recv_timeout") unable to return data when called. This can occur with both a [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") and a [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") . [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") This enumeration is the list of the possible reasons that [`try_recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_recv "method std::sync::mpsc::Receiver::try_recv") could not return data when called. This can occur with both a [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") and a [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") . [TrySendError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TrySendError.html "enum std::sync::mpsc::TrySendError") This enumeration is the list of the possible error outcomes for the [`try_send`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html#method.try_send "method std::sync::mpsc::SyncSender::try_send") method. Functions[§](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html#functions) ---------------------------------------------------------------------------------- [channel](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") Creates a new asynchronous channel, returning the sender/receiver halves. [sync\_channel](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") Creates a new synchronous, bounded channel. --- # std::u8 - Rust [Module u8](https://doc.rust-lang.org/stable/std/u8/index.html#) ----------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module u8 Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#70) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`u8` primitive type](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/u8/index.html#constants) --------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/u8/constant.MAX.html "constant std::u8::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`u8::MAX`](https://doc.rust-lang.org/stable/std/primitive.u8.html#associatedconstant.MAX "associated constant u8::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/u8/constant.MIN.html "constant std::u8::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`u8::MIN`](https://doc.rust-lang.org/stable/std/primitive.u8.html#associatedconstant.MIN "associated constant u8::MIN") instead. --- # std::u16 - Rust [Module u16](https://doc.rust-lang.org/stable/std/u16/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module u16 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#67) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`u16` primitive type](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive u16") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/u16/index.html#constants) ---------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/u16/constant.MAX.html "constant std::u16::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`u16::MAX`](https://doc.rust-lang.org/stable/std/primitive.u16.html#associatedconstant.MAX "associated constant u16::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/u16/constant.MIN.html "constant std::u16::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`u16::MIN`](https://doc.rust-lang.org/stable/std/primitive.u16.html#associatedconstant.MIN "associated constant u16::MIN") instead. --- # std::u32 - Rust [Module u32](https://doc.rust-lang.org/stable/std/u32/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module u32 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#68) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`u32` primitive type](https://doc.rust-lang.org/stable/std/primitive.u32.html "primitive u32") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/u32/index.html#constants) ---------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/u32/constant.MAX.html "constant std::u32::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`u32::MAX`](https://doc.rust-lang.org/stable/std/primitive.u32.html#associatedconstant.MAX "associated constant u32::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/u32/constant.MIN.html "constant std::u32::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`u32::MIN`](https://doc.rust-lang.org/stable/std/primitive.u32.html#associatedconstant.MIN "associated constant u32::MIN") instead. --- # std::u64 - Rust [Module u64](https://doc.rust-lang.org/stable/std/u64/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module u64 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#69) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`u64` primitive type](https://doc.rust-lang.org/stable/std/primitive.u64.html "primitive u64") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/u64/index.html#constants) ---------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/u64/constant.MAX.html "constant std::u64::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`u64::MAX`](https://doc.rust-lang.org/stable/std/primitive.u64.html#associatedconstant.MAX "associated constant u64::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/u64/constant.MIN.html "constant std::u64::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`u64::MIN`](https://doc.rust-lang.org/stable/std/primitive.u64.html#associatedconstant.MIN "associated constant u64::MIN") instead. --- # std::u128 - Rust [Module u128](https://doc.rust-lang.org/stable/std/u128/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module u128 Copy item path ========================== 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#66) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`u128` primitive type](https://doc.rust-lang.org/stable/std/primitive.u128.html "primitive u128") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/u128/index.html#constants) ----------------------------------------------------------------------------- [MAX](https://doc.rust-lang.org/stable/std/u128/constant.MAX.html "constant std::u128::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`u128::MAX`](https://doc.rust-lang.org/stable/std/primitive.u128.html#associatedconstant.MAX "associated constant u128::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/u128/constant.MIN.html "constant std::u128::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`u128::MIN`](https://doc.rust-lang.org/stable/std/primitive.u128.html#associatedconstant.MIN "associated constant u128::MIN") instead. --- # std::usize - Rust [Module usize](https://doc.rust-lang.org/stable/std/usize/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module usize Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/shells/legacy_int_modules.rs.html#71) 👎Deprecating in a future version: all constants in this module replaced by associated constants on the type Expand description Redundant constants module for the [`usize` primitive type](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") . New code should use the associated constants directly on the primitive type. Constants[§](https://doc.rust-lang.org/stable/std/usize/index.html#constants) ------------------------------------------------------------------------------ [MAX](https://doc.rust-lang.org/stable/std/usize/constant.MAX.html "constant std::usize::MAX") Deprecation planned The largest value that can be represented by this integer type. Use [`usize::MAX`](https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.MAX "associated constant usize::MAX") instead. [MIN](https://doc.rust-lang.org/stable/std/usize/constant.MIN.html "constant std::usize::MIN") Deprecation planned The smallest value that can be represented by this integer type. Use [`usize::MIN`](https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.MIN "associated constant usize::MIN") instead. --- # std::autodiff - Rust [Module autodiff](https://doc.rust-lang.org/stable/std/autodiff/index.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module autodiff Copy item path ============================== [Source](https://doc.rust-lang.org/stable/src/std/lib.rs.html#639) 🔬This is a nightly-only experimental API. (`autodiff` [#124509](https://github.com/rust-lang/rust/issues/124509) ) Expand description This module provides support for automatic differentiation. Attribute Macros[§](https://doc.rust-lang.org/stable/std/autodiff/index.html#attributes) ----------------------------------------------------------------------------------------- [autodiff\_forward](https://doc.rust-lang.org/stable/std/autodiff/attr.autodiff_forward.html "attr std::autodiff::autodiff_forward") Experimental This macro handles automatic differentiation. This macro uses forward-mode automatic differentiation to generate a new function. It may only be applied to a function. The new function will compute the derivative of the function to which the macro was applied. [autodiff\_reverse](https://doc.rust-lang.org/stable/std/autodiff/attr.autodiff_reverse.html "attr std::autodiff::autodiff_reverse") Experimental This macro handles automatic differentiation. This macro uses reverse-mode automatic differentiation to generate a new function. It may only be applied to a function. The new function will compute the derivative of the function to which the macro was applied. --- # std::bstr - Rust [Module bstr](https://doc.rust-lang.org/stable/std/bstr/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module bstr Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/bstr.rs.html#1-4) 🔬This is a nightly-only experimental API. (`bstr` [#134915](https://github.com/rust-lang/rust/issues/134915) ) Expand description The `ByteStr` and `ByteString` types and trait implementations. Structs[§](https://doc.rust-lang.org/stable/std/bstr/index.html#structs) ------------------------------------------------------------------------- [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") Experimental A wrapper for `&[u8]` representing a human-readable string that’s conventionally, but not always, UTF-8. [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") Experimental A wrapper for `Vec` representing a human-readable string that’s conventionally, but not always, UTF-8. --- # std::f16 - Rust [Module f16](https://doc.rust-lang.org/stable/std/f16/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module f16 Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/std/num/f16.rs.html#1-1044) 🔬This is a nightly-only experimental API. (`f16` [#116909](https://github.com/rust-lang/rust/issues/116909) ) Expand description Constants for the `f16` half-precision floating point type. _[See also the `f16` primitive type](https://doc.rust-lang.org/stable/std/primitive.f16.html "primitive f16") ._ Mathematically significant numbers are provided in the `consts` sub-module. Modules[§](https://doc.rust-lang.org/stable/std/f16/index.html#modules) ------------------------------------------------------------------------ [consts](https://doc.rust-lang.org/stable/std/f16/consts/index.html "mod std::f16::consts") Experimental Basic mathematical constants. --- # std::f128 - Rust [Module f128](https://doc.rust-lang.org/stable/std/f128/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module f128 Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/num/f128.rs.html#1-1079) 🔬This is a nightly-only experimental API. (`f128` [#116909](https://github.com/rust-lang/rust/issues/116909) ) Expand description Constants for the `f128` quadruple-precision floating point type. _[See also the `f128` primitive type](https://doc.rust-lang.org/stable/std/primitive.f128.html "primitive f128") ._ Mathematically significant numbers are provided in the `consts` sub-module. Modules[§](https://doc.rust-lang.org/stable/std/f128/index.html#modules) ------------------------------------------------------------------------- [consts](https://doc.rust-lang.org/stable/std/f128/consts/index.html "mod std::f128::consts") Experimental Basic mathematical constants. --- # std::pat - Rust [Module pat](https://doc.rust-lang.org/stable/std/pat/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module pat Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/std/pat.rs.html#1-3) 🔬This is a nightly-only experimental API. (`pattern_type_macro` [#123646](https://github.com/rust-lang/rust/issues/123646) ) Expand description Helper module for exporting the `pattern_type` macro Macros[§](https://doc.rust-lang.org/stable/std/pat/index.html#macros) ---------------------------------------------------------------------- [pattern\_type](https://doc.rust-lang.org/stable/std/pat/macro.pattern_type.html "macro std::pat::pattern_type") Experimental Creates a pattern type. --- # concat in std - Rust [concat](https://doc.rust-lang.org/stable/std/macro.concat.html#) ------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro concat Copy item path =========================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1152) macro_rules! concat { ($($e:expr),* $(,)?) => { ... }; } Expand description Concatenates literals into a static string slice. This macro takes any number of comma-separated literals, yielding an expression of type `&'static str` which represents all of the literals concatenated left-to-right. Integer and floating point literals are [stringified](https://doc.rust-lang.org/stable/std/macro.stringify.html "macro std::stringify") in order to be concatenated. [§](https://doc.rust-lang.org/stable/std/macro.concat.html#examples) Examples ----------------------------------------------------------------------------- let s = concat!("test", 10, 'b', true); assert_eq!(s, "test10btrue"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+s+=+concat!(%22test%22,+10,+%27b%27,+true);%0A++++assert_eq!(s,+%22test10btrue%22);%0A%7D&edition=2024 "Run code") --- # compile_error in std - Rust [compile\_error](https://doc.rust-lang.org/stable/std/macro.compile_error.html#) --------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro compile\_error Copy item path =================================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#929) macro_rules! compile_error { ($msg:expr $(,)?) => { ... }; } Expand description Causes compilation to fail with the given error message when encountered. This macro should be used when a crate uses a conditional compilation strategy to provide better error messages for erroneous conditions. It’s the compiler-level form of [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") , but emits an error during _compilation_ rather than at _runtime_. [§](https://doc.rust-lang.org/stable/std/macro.compile_error.html#examples) Examples ------------------------------------------------------------------------------------ Two such examples are macros and `#[cfg]` environments. Emit a better compiler error if a macro is passed invalid values. Without the final branch, the compiler would still emit an error, but the error’s message would not mention the two valid values. [ⓘ](https://doc.rust-lang.org/stable/std/macro.compile_error.html# "This example deliberately fails to compile") macro_rules! give_me_foo_or_bar { (foo) => {}; (bar) => {}; ($x:ident) => { compile_error!("This macro only accepts `foo` or `bar`"); } } give_me_foo_or_bar!(neither); // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++macro_rules!+give_me_foo_or_bar+%7B%0A++++++++(foo)+=%3E+%7B%7D;%0A++++++++(bar)+=%3E+%7B%7D;%0A++++++++(%24x:ident)+=%3E+%7B%0A++++++++++++compile_error!(%22This+macro+only+accepts+%60foo%60+or+%60bar%60%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++give_me_foo_or_bar!(neither);%0A%7D&edition=2024 "Run code") Emit a compiler error if one of a number of features isn’t available. [ⓘ](https://doc.rust-lang.org/stable/std/macro.compile_error.html# "This example deliberately fails to compile") #[cfg(not(any(feature = "foo", feature = "bar")))] compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate."); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bcfg(not(any(feature+=+%22foo%22,+feature+=+%22bar%22)))%5D%0A++++compile_error!(%22Either+feature+%5C%22foo%5C%22+or+%5C%22bar%5C%22+must+be+enabled+for+this+crate.%22);%0A%7D&edition=2024 "Run code") --- # dbg in std - Rust [dbg](https://doc.rust-lang.org/stable/std/macro.dbg.html#) ------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro dbg Copy item path ======================== 1.32.0 · [Source](https://doc.rust-lang.org/stable/src/std/macros.rs.html#352-381) macro_rules! dbg { () => { ... }; ($val:expr $(,)?) => { ... }; ($($val:expr),+ $(,)?) => { ... }; } Expand description Prints and returns the value of a given expression for quick and dirty debugging. An example: let a = 2; let b = dbg!(a * 2) + 1; // ^-- prints: [src/main.rs:2:9] a * 2 = 4 assert_eq!(b, 5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+2;%0A++++let+b+=+dbg!(a+*+2)+%2B+1;%0A++++//++++++%5E--+prints:+%5Bsrc/main.rs:2:9%5D+a+*+2+=+4%0A++++assert_eq!(b,+5);%0A%7D&edition=2024 "Run code") The macro works by using the `Debug` implementation of the type of the given expression to print the value to [stderr](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) along with the source location of the macro invocation as well as the source code of the expression. Invoking the macro on an expression moves and takes ownership of it before returning the evaluated expression unchanged. If the type of the expression does not implement `Copy` and you don’t want to give up ownership, you can instead borrow with `dbg!(&expr)` for some expression `expr`. The `dbg!` macro works exactly the same in release builds. This is useful when debugging issues that only occur in release builds or when debugging in release mode is significantly faster. Note that the macro is intended as a debugging tool and therefore you should avoid having uses of it in version control for long periods (other than in tests and similar). Debug output from production code is better done with other facilities such as the [`debug!`](https://docs.rs/log/*/log/macro.debug.html) macro from the [`log`](https://crates.io/crates/log) crate. [§](https://doc.rust-lang.org/stable/std/macro.dbg.html#stability) Stability ---------------------------------------------------------------------------- The exact output printed by this macro should not be relied upon and is subject to future changes. [§](https://doc.rust-lang.org/stable/std/macro.dbg.html#panics) Panics ---------------------------------------------------------------------- Panics if writing to `io::stderr` fails. [§](https://doc.rust-lang.org/stable/std/macro.dbg.html#further-examples) Further examples ------------------------------------------------------------------------------------------ With a method call: fn foo(n: usize) { if let Some(_) = dbg!(n.checked_sub(4)) { // ... } } foo(3) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+foo(n:+usize)+%7B%0A++++++++if+let+Some(_)+=+dbg!(n.checked_sub(4))+%7B%0A++++++++++++//+...%0A++++++++%7D%0A++++%7D%0A++++%0A++++foo(3)%0A%7D&edition=2024 "Run code") This prints to [stderr](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) : [src/main.rs:2:22] n.checked_sub(4) = None Naive factorial implementation: fn factorial(n: u32) -> u32 { if dbg!(n <= 1) { dbg!(1) } else { dbg!(n * factorial(n - 1)) } } dbg!(factorial(4)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+factorial(n:+u32)+-%3E+u32+%7B%0A++++++++if+dbg!(n+%3C=+1)+%7B%0A++++++++++++dbg!(1)%0A++++++++%7D+else+%7B%0A++++++++++++dbg!(n+*+factorial(n+-+1))%0A++++++++%7D%0A++++%7D%0A++++%0A++++dbg!(factorial(4));%0A%7D&edition=2024 "Run code") This prints to [stderr](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) : [src/main.rs:2:8] n <= 1 = false [src/main.rs:2:8] n <= 1 = false [src/main.rs:2:8] n <= 1 = false [src/main.rs:2:8] n <= 1 = true [src/main.rs:3:9] 1 = 1 [src/main.rs:7:9] n * factorial(n - 1) = 2 [src/main.rs:7:9] n * factorial(n - 1) = 6 [src/main.rs:7:9] n * factorial(n - 1) = 24 [src/main.rs:9:1] factorial(4) = 24 The `dbg!(..)` macro moves the input: [ⓘ](https://doc.rust-lang.org/stable/std/macro.dbg.html# "This example deliberately fails to compile") /// A wrapper around `usize` which importantly is not Copyable. #[derive(Debug)] struct NoCopy(usize); let a = NoCopy(42); let _ = dbg!(a); // <-- `a` is moved here. let _ = dbg!(a); // <-- `a` is moved again; error! [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++///+A+wrapper+around+%60usize%60+which+importantly+is+not+Copyable.%0A++++%23%5Bderive(Debug)%5D%0A++++struct+NoCopy(usize);%0A++++%0A++++let+a+=+NoCopy(42);%0A++++let+_+=+dbg!(a);+//+%3C--+%60a%60+is+moved+here.%0A++++let+_+=+dbg!(a);%0A%7D&edition=2024 "Run code") You can also use `dbg!()` without a value to just print the file and line whenever it’s reached. Finally, if you want to `dbg!(..)` multiple values, it will treat them as a tuple (and return it, too): assert_eq!(dbg!(1usize, 2u32), (1, 2)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(dbg!(1usize,+2u32),+(1,+2));%0A%7D&edition=2024 "Run code") However, a single argument with a trailing comma will still not be treated as a tuple, following the convention of ignoring trailing commas in macro invocations. You can use a 1-tuple directly if you need one: assert_eq!(1, dbg!(1u32,)); // trailing comma ignored assert_eq!((1,), dbg!((1u32,))); // 1-tuple [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1,+dbg!(1u32,));+//+trailing+comma+ignored%0A++++assert_eq!((1,),+dbg!((1u32,)));%0A%7D&edition=2024 "Run code") --- # std::convert - Rust [Module convert](https://doc.rust-lang.org/stable/std/convert/index.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module convert Copy item path ============================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#293) Expand description Traits for conversions between types. The traits in this module provide a way to convert from one type to another type. Each trait serves a different purpose: * Implement the [`AsRef`](https://doc.rust-lang.org/stable/std/convert/trait.AsRef.html "trait std::convert::AsRef") trait for cheap reference-to-reference conversions * Implement the [`AsMut`](https://doc.rust-lang.org/stable/std/convert/trait.AsMut.html "trait std::convert::AsMut") trait for cheap mutable-to-mutable conversions * Implement the [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") trait for consuming value-to-value conversions * Implement the [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") trait for consuming value-to-value conversions to types outside the current crate * The [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") and [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") traits behave like [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") and [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , but should be implemented when the conversion can fail. The traits in this module are often used as trait bounds for generic functions such that to arguments of multiple types are supported. See the documentation of each trait for examples. As a library author, you should always prefer implementing [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") or [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") rather than [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") or [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") , as [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") and [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") provide greater flexibility and offer equivalent [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") or [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") implementations for free, thanks to a blanket implementation in the standard library. When targeting a version prior to Rust 1.41, it may be necessary to implement [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") or [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") directly when converting to a type outside the current crate. [§](https://doc.rust-lang.org/stable/std/convert/index.html#generic-implementations) Generic Implementations ------------------------------------------------------------------------------------------------------------ * [`AsRef`](https://doc.rust-lang.org/stable/std/convert/trait.AsRef.html "trait std::convert::AsRef") and [`AsMut`](https://doc.rust-lang.org/stable/std/convert/trait.AsMut.html "trait std::convert::AsMut") auto-dereference if the inner type is a reference (but not generally for all [dereferenceable types](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") ) * [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") ` for T` implies [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") ` for U` * [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") ` for T` implies [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") ` for U` * [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") and [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") are reflexive, which means that all types can `into` themselves and `from` themselves See each trait for usage examples. Enums[§](https://doc.rust-lang.org/stable/std/convert/index.html#enums) ------------------------------------------------------------------------ [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The error type for errors that can never happen. Traits[§](https://doc.rust-lang.org/stable/std/convert/index.html#traits) -------------------------------------------------------------------------- [AsMut](https://doc.rust-lang.org/stable/std/convert/trait.AsMut.html "trait std::convert::AsMut") Used to do a cheap mutable-to-mutable reference conversion. [AsRef](https://doc.rust-lang.org/stable/std/convert/trait.AsRef.html "trait std::convert::AsRef") Used to do a cheap reference-to-reference conversion. [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") Used to do value-to-value conversions while consuming the input value. It is the reciprocal of [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") . [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") A value-to-value conversion that consumes the input value. The opposite of [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") . [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") Simple and safe type conversions that may fail in a controlled way under some circumstances. It is the reciprocal of [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") . [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") An attempted conversion that consumes `self`, which may or may not be expensive. [FloatToInt](https://doc.rust-lang.org/stable/std/convert/trait.FloatToInt.html "trait std::convert::FloatToInt") Experimental Supporting trait for inherent methods of `f32` and `f64` such as `to_int_unchecked`. Typically doesn’t need to be used directly. Functions[§](https://doc.rust-lang.org/stable/std/convert/index.html#functions) -------------------------------------------------------------------------------- [identity](https://doc.rust-lang.org/stable/std/convert/fn.identity.html "fn std::convert::identity") The identity function. --- # std::hint - Rust [Module hint](https://doc.rust-lang.org/stable/std/hint/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module hint Copy item path ========================== 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#281) Expand description Hints to compiler that affects how code should be emitted or optimized. Hints may be compile time or runtime. Functions[§](https://doc.rust-lang.org/stable/std/hint/index.html#functions) ----------------------------------------------------------------------------- [assert\_unchecked](https://doc.rust-lang.org/stable/std/hint/fn.assert_unchecked.html "fn std::hint::assert_unchecked") ⚠ Makes a _soundness_ promise to the compiler that `cond` holds. [black\_box](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html "fn std::hint::black_box") An identity function that _**hints**_ to the compiler to be maximally pessimistic about what `black_box` could do. [select\_unpredictable](https://doc.rust-lang.org/stable/std/hint/fn.select_unpredictable.html "fn std::hint::select_unpredictable") Returns either `true_val` or `false_val` depending on the value of `condition`, with a hint to the compiler that `condition` is unlikely to be correctly predicted by a CPU’s branch predictor. [spin\_loop](https://doc.rust-lang.org/stable/std/hint/fn.spin_loop.html "fn std::hint::spin_loop") Emits a machine instruction to signal the processor that it is running in a busy-wait spin-loop (“spin lock”). [unreachable\_unchecked](https://doc.rust-lang.org/stable/std/hint/fn.unreachable_unchecked.html "fn std::hint::unreachable_unchecked") ⚠ Informs the compiler that the site which is calling this function is not reachable, possibly enabling further optimizations. [cold\_path](https://doc.rust-lang.org/stable/std/hint/fn.cold_path.html "fn std::hint::cold_path") Experimental Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may choose to optimize paths that are not cold at the expense of paths that are cold. [likely](https://doc.rust-lang.org/stable/std/hint/fn.likely.html "fn std::hint::likely") Experimental Hints to the compiler that a branch condition is likely to be true. Returns the value passed to it. [must\_use](https://doc.rust-lang.org/stable/std/hint/fn.must_use.html "fn std::hint::must_use") Experimental An identity function that causes an `unused_must_use` warning to be triggered if the given value is not used (returned, stored in a variable, etc) by the caller. [unlikely](https://doc.rust-lang.org/stable/std/hint/fn.unlikely.html "fn std::hint::unlikely") Experimental Hints to the compiler that a branch condition is unlikely to be true. Returns the value passed to it. --- # std::unsafe_binder - Rust [Module unsafe\_binder](https://doc.rust-lang.org/stable/std/unsafe_binder/index.html#) ---------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module unsafe\_binder Copy item path ==================================== [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#330) 🔬This is a nightly-only experimental API. (`unsafe_binders` [#130516](https://github.com/rust-lang/rust/issues/130516) ) Expand description Operators used to turn types into unsafe binders and back. Macros[§](https://doc.rust-lang.org/stable/std/unsafe_binder/index.html#macros) -------------------------------------------------------------------------------- [unwrap\_binder](https://doc.rust-lang.org/stable/std/unsafe_binder/macro.unwrap_binder.html "macro std::unsafe_binder::unwrap_binder") Experimental Unwrap an unsafe binder into its underlying type. [wrap\_binder](https://doc.rust-lang.org/stable/std/unsafe_binder/macro.wrap_binder.html "macro std::unsafe_binder::wrap_binder") Experimental Wrap a type into an unsafe binder. --- # column in std - Rust [column](https://doc.rust-lang.org/stable/std/macro.column.html#) ------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro column Copy item path =========================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1216) macro_rules! column { () => { ... }; } Expand description Expands to the column number at which it was invoked. With [`line!`](https://doc.rust-lang.org/stable/std/macro.line.html "macro std::line") and [`file!`](https://doc.rust-lang.org/stable/std/macro.file.html "macro std::file") , these macros provide debugging information for developers about the location within the source. The expanded expression has type `u32` and is 1-based, so the first column in each line evaluates to 1, the second to 2, etc. This is consistent with error messages by common compilers or popular editors. The returned column is _not necessarily_ the line of the `column!` invocation itself, but rather the first macro invocation leading up to the invocation of the `column!` macro. [§](https://doc.rust-lang.org/stable/std/macro.column.html#examples) Examples ----------------------------------------------------------------------------- let current_col = column!(); println!("defined on column: {current_col}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+current_col+=+column!();%0A++++println!(%22defined+on+column:+%7Bcurrent_col%7D%22);%0A%7D&edition=2024 "Run code") `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two invocations return the same value, but the third does not. let a = ("foobar", column!()).1; let b = ("人之初性本善", column!()).1; let c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305) assert_eq!(a, b); assert_ne!(b, c); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+(%22foobar%22,+column!()).1;%0A++++let+b+=+(%22%E4%BA%BA%E4%B9%8B%E5%88%9D%E6%80%A7%E6%9C%AC%E5%96%84%22,+column!()).1;%0A++++let+c+=+(%22f%CC%85o%CC%85o%CC%85b%CC%85a%CC%85r%CC%85%22,+column!()).1;+//+Uses+combining+overline+(U%2B0305)%0A++++%0A++++assert_eq!(a,+b);%0A++++assert_ne!(b,+c);%0A%7D&edition=2024 "Run code") --- # debug_assert_eq in std - Rust [debug\_assert\_eq](https://doc.rust-lang.org/stable/std/macro.debug_assert_eq.html#) -------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro debug\_assert\_eq Copy item path ====================================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#322) macro_rules! debug_assert_eq { ($($arg:tt)*) => { ... }; } Expand description Asserts that two expressions are equal to each other. On panic, this macro will print the values of the expressions with their debug representations. Unlike [`assert_eq!`](https://doc.rust-lang.org/stable/std/macro.assert_eq.html "macro std::assert_eq") , `debug_assert_eq!` statements are only enabled in non optimized builds by default. An optimized build will not execute `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the compiler. This makes `debug_assert_eq!` useful for checks that are too expensive to be present in a release build but may be helpful during development. The result of expanding `debug_assert_eq!` is always type checked. [§](https://doc.rust-lang.org/stable/std/macro.debug_assert_eq.html#examples) Examples -------------------------------------------------------------------------------------- let a = 3; let b = 1 + 2; debug_assert_eq!(a, b); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+3;%0A++++let+b+=+1+%2B+2;%0A++++debug_assert_eq!(a,+b);%0A%7D&edition=2024 "Run code") --- # debug_assert_ne in std - Rust [debug\_assert\_ne](https://doc.rust-lang.org/stable/std/macro.debug_assert_ne.html#) -------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro debug\_assert\_ne Copy item path ====================================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#352) macro_rules! debug_assert_ne { ($($arg:tt)*) => { ... }; } Expand description Asserts that two expressions are not equal to each other. On panic, this macro will print the values of the expressions with their debug representations. Unlike [`assert_ne!`](https://doc.rust-lang.org/stable/std/macro.assert_ne.html "macro std::assert_ne") , `debug_assert_ne!` statements are only enabled in non optimized builds by default. An optimized build will not execute `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the compiler. This makes `debug_assert_ne!` useful for checks that are too expensive to be present in a release build but may be helpful during development. The result of expanding `debug_assert_ne!` is always type checked. [§](https://doc.rust-lang.org/stable/std/macro.debug_assert_ne.html#examples) Examples -------------------------------------------------------------------------------------- let a = 3; let b = 2; debug_assert_ne!(a, b); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+3;%0A++++let+b+=+2;%0A++++debug_assert_ne!(a,+b);%0A%7D&edition=2024 "Run code") --- # std::collections - Rust [Module collections](https://doc.rust-lang.org/stable/std/collections/index.html#) ----------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module collections Copy item path ================================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/collections/mod.rs.html#1-459) Expand description Collection types. Rust’s standard collection library provides efficient implementations of the most common general purpose programming data structures. By using the standard implementations, it should be possible for two libraries to communicate without significant data conversion. To get this out of the way: you should probably just use [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") or [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") . These two collections cover most use cases for generic data storage and processing. They are exceptionally good at doing what they do. All the other collections in the standard library have specific use cases where they are the optimal choice, but these cases are borderline _niche_ in comparison. Even when `Vec` and `HashMap` are technically suboptimal, they’re probably a good enough choice to get started. Rust’s collections can be grouped into four major categories: * Sequences: [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") , [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") , [`LinkedList`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") * Maps: [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") , [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") * Sets: [`HashSet`](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html "struct std::collections::HashSet") , [`BTreeSet`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html "struct std::collections::BTreeSet") * Misc: [`BinaryHeap`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") [§](https://doc.rust-lang.org/stable/std/collections/index.html#when-should-you-use-which-collection) When Should You Use Which Collection? ------------------------------------------------------------------------------------------------------------------------------------------- These are fairly high-level and quick break-downs of when each collection should be considered. Detailed discussions of strengths and weaknesses of individual collections can be found on their own documentation pages. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-vec-when) Use a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") when: * You want to collect items up to be processed or sent elsewhere later, and don’t care about any properties of the actual values being stored. * You want a sequence of elements in a particular order, and will only be appending to (or near) the end. * You want a stack. * You want a resizable array. * You want a heap-allocated array. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-vecdeque-when) Use a [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") when: * You want a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") that supports efficient insertion at both ends of the sequence. * You want a queue. * You want a double-ended queue (deque). #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-linkedlist-when) Use a [`LinkedList`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") when: * You want a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") or [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") of unknown size, and can’t tolerate amortization. * You want to efficiently split and append lists. * You are _absolutely_ certain you _really_, _truly_, want a doubly linked list. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-hashmap-when) Use a [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") when: * You want to associate arbitrary keys with an arbitrary value. * You want a cache. * You want a map, with no extra functionality. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-btreemap-when) Use a [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") when: * You want a map sorted by its keys. * You want to be able to get a range of entries on-demand. * You’re interested in what the smallest or largest key-value pair is. * You want to find the largest or smallest key that is smaller or larger than something. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-the-set-variant-of-any-of-these-maps-when) Use the `Set` variant of any of these `Map`s when: * You just want to remember which keys you’ve seen. * There is no meaningful value to associate with your keys. * You just want a set. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-binaryheap-when) Use a [`BinaryHeap`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") when: * You want to store a bunch of elements, but only ever want to process the “biggest” or “most important” one at any given time. * You want a priority queue. [§](https://doc.rust-lang.org/stable/std/collections/index.html#performance) Performance ---------------------------------------------------------------------------------------- Choosing the right collection for the job requires an understanding of what each collection is good at. Here we briefly summarize the performance of different collections for certain important operations. For further details, see each type’s documentation, and note that the names of actual methods may differ from the tables below on certain collections. Throughout the documentation, we will adhere to the following conventions for operation notation: * The collection’s size is denoted by `n`. * If a second collection is involved, its size is denoted by `m`. * Item indices are denoted by `i`. * Operations which have an _amortized_ cost are suffixed with a `*`. * Operations with an _expected_ cost are suffixed with a `~`. Calling operations that add to a collection will occasionally require a collection to be resized - an extra operation that takes _O_(_n_) time. _Amortized_ costs are calculated to account for the time cost of such resize operations _over a sufficiently large series of operations_. An individual operation may be slower or faster due to the sporadic nature of collection resizing, however the average cost per operation will approach the amortized cost. Rust’s collections never automatically shrink, so removal operations aren’t amortized. [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") uses _expected_ costs. It is theoretically possible, though very unlikely, for [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") to experience significantly worse performance than the expected cost. This is due to the probabilistic nature of hashing - i.e. it is possible to generate a duplicate hash given some input key that will requires extra computation to correct. ### [§](https://doc.rust-lang.org/stable/std/collections/index.html#cost-of-collection-operations) Cost of Collection Operations | | get(i) | insert(i) | remove(i) | append(Vec(m)) | split\_off(i) | range | append | | --- | --- | --- | --- | --- | --- | --- | --- | | [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") | _O_(1) | _O_(_n_\-_i_)\* | _O_(_n_\-_i_) | _O_(_m_)\* | _O_(_n_\-_i_) | N/A | N/A | | [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") | _O_(1) | _O_(min(_i_, _n_\-_i_))\* | _O_(min(_i_, _n_\-_i_)) | _O_(_m_)\* | _O_(min(_i_, _n_\-_i_)) | N/A | N/A | | [`LinkedList`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") | _O_(min(_i_, _n_\-_i_)) | _O_(min(_i_, _n_\-_i_)) | _O_(min(_i_, _n_\-_i_)) | _O_(1) | _O_(min(_i_, _n_\-_i_)) | N/A | N/A | | [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") | _O_(1)~ | _O_(1)~\* | _O_(1)~ | N/A | N/A | N/A | N/A | | [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") | _O_(log(_n_)) | _O_(log(_n_)) | _O_(log(_n_)) | N/A | N/A | _O_(log(_n_)) | _O_(_n_+_m_) | Note that where ties occur, [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") is generally going to be faster than [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") , and [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") is generally going to be faster than [`LinkedList`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") . For Sets, all operations have the cost of the equivalent Map operation. [§](https://doc.rust-lang.org/stable/std/collections/index.html#correct-and-efficient-usage-of-collections) Correct and Efficient Usage of Collections ------------------------------------------------------------------------------------------------------------------------------------------------------ Of course, knowing which collection is the right one for the job doesn’t instantly permit you to use it correctly. Here are some quick tips for efficient and correct usage of the standard collections in general. If you’re interested in how to use a specific collection in particular, consult its documentation for detailed discussion and code examples. ### [§](https://doc.rust-lang.org/stable/std/collections/index.html#capacity-management) Capacity Management Many collections provide several constructors and methods that refer to “capacity”. These collections are generally built on top of an array. Optimally, this array would be exactly the right size to fit only the elements stored in the collection, but for the collection to do this would be very inefficient. If the backing array was exactly the right size at all times, then every time an element is inserted, the collection would have to grow the array to fit it. Due to the way memory is allocated and managed on most computers, this would almost surely require allocating an entirely new array and copying every single element from the old one into the new one. Hopefully you can see that this wouldn’t be very efficient to do on every operation. Most collections therefore use an _amortized_ allocation strategy. They generally let themselves have a fair amount of unoccupied space so that they only have to grow on occasion. When they do grow, they allocate a substantially larger array to move the elements into so that it will take a while for another grow to be required. While this strategy is great in general, it would be even better if the collection _never_ had to resize its backing array. Unfortunately, the collection itself doesn’t have enough information to do this itself. Therefore, it is up to us programmers to give it hints. Any `with_capacity` constructor will instruct the collection to allocate enough space for the specified number of elements. Ideally this will be for exactly that many elements, but some implementation details may prevent this. See collection-specific documentation for details. In general, use `with_capacity` when you know exactly how many elements will be inserted, or at least have a reasonable upper-bound on that number. When anticipating a large influx of elements, the `reserve` family of methods can be used to hint to the collection how much room it should make for the coming items. As with `with_capacity`, the precise behavior of these methods will be specific to the collection of interest. For optimal performance, collections will generally avoid shrinking themselves. If you believe that a collection will not soon contain any more elements, or just really need the memory, the `shrink_to_fit` method prompts the collection to shrink the backing array to the minimum size capable of holding its elements. Finally, if ever you’re interested in what the actual capacity of the collection is, most collections provide a `capacity` method to query this information on demand. This can be useful for debugging purposes, or for use with the `reserve` methods. ### [§](https://doc.rust-lang.org/stable/std/collections/index.html#iterators) Iterators [Iterators](https://doc.rust-lang.org/stable/std/iter/index.html "mod std::iter") are a powerful and robust mechanism used throughout Rust’s standard libraries. Iterators provide a sequence of values in a generic, safe, efficient and convenient way. The contents of an iterator are usually _lazily_ evaluated, so that only the values that are actually needed are ever actually produced, and no allocation need be done to temporarily store them. Iterators are primarily consumed using a `for` loop, although many functions also take iterators where a collection or sequence of values is desired. All of the standard collections provide several iterators for performing bulk manipulation of their contents. The three primary iterators almost every collection should provide are `iter`, `iter_mut`, and `into_iter`. Some of these are not provided on collections where it would be unsound or unreasonable to provide them. `iter` provides an iterator of immutable references to all the contents of a collection in the most “natural” order. For sequence collections like [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") , this means the items will be yielded in increasing order of index starting at 0. For ordered collections like [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") , this means that the items will be yielded in sorted order. For unordered collections like [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") , the items will be yielded in whatever order the internal representation made most convenient. This is great for reading through all the contents of the collection. let vec = vec![1, 2, 3, 4]; for x in vec.iter() { println!("vec contained {x:?}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+vec+=+vec!%5B1,+2,+3,+4%5D;%0A++++for+x+in+vec.iter()+%7B%0A+++++++println!(%22vec+contained+%7Bx:?%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") `iter_mut` provides an iterator of _mutable_ references in the same order as `iter`. This is great for mutating all the contents of the collection. let mut vec = vec![1, 2, 3, 4]; for x in vec.iter_mut() { *x += 1; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+vec+=+vec!%5B1,+2,+3,+4%5D;%0A++++for+x+in+vec.iter_mut()+%7B%0A+++++++*x+%2B=+1;%0A++++%7D%0A%7D&edition=2024 "Run code") `into_iter` transforms the actual collection into an iterator over its contents by-value. This is great when the collection itself is no longer needed, and the values are needed elsewhere. Using `extend` with `into_iter` is the main way that contents of one collection are moved into another. `extend` automatically calls `into_iter`, and takes any `T: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") `. Calling `collect` on an iterator itself is also a great way to convert one collection into another. Both of these methods should internally use the capacity management tools discussed in the previous section to do this as efficiently as possible. let mut vec1 = vec![1, 2, 3, 4]; let vec2 = vec![10, 20, 30, 40]; vec1.extend(vec2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+vec1+=+vec!%5B1,+2,+3,+4%5D;%0A++++let+vec2+=+vec!%5B10,+20,+30,+40%5D;%0A++++vec1.extend(vec2);%0A%7D&edition=2024 "Run code") use std::collections::VecDeque; let vec = [1, 2, 3, 4]; let buf: VecDeque<_> = vec.into_iter().collect(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::VecDeque;%0A++++%0A++++let+vec+=+%5B1,+2,+3,+4%5D;%0A++++let+buf:+VecDeque%3C_%3E+=+vec.into_iter().collect();%0A%7D&edition=2024 "Run code") Iterators also provide a series of _adapter_ methods for performing common threads to sequences. Among the adapters are functional favorites like `map`, `fold`, `skip` and `take`. Of particular interest to collections is the `rev` adapter, which reverses any iterator that supports this operation. Most collections provide reversible iterators as the way to iterate over them in reverse order. let vec = vec![1, 2, 3, 4]; for x in vec.iter().rev() { println!("vec contained {x:?}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+vec+=+vec!%5B1,+2,+3,+4%5D;%0A++++for+x+in+vec.iter().rev()+%7B%0A+++++++println!(%22vec+contained+%7Bx:?%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") Several other collection methods also return iterators to yield a sequence of results but avoid allocating an entire collection to store the result in. This provides maximum flexibility as [`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect "method std::iter::Iterator::collect") or [`extend`](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend "method std::iter::Extend::extend") can be called to “pipe” the sequence into any collection if desired. Otherwise, the sequence can be looped over with a `for` loop. The iterator can also be discarded after partial use, preventing the computation of the unused items. ### [§](https://doc.rust-lang.org/stable/std/collections/index.html#entries) Entries The `entry` API is intended to provide an efficient mechanism for manipulating the contents of a map conditionally on the presence of a key or not. The primary motivating use case for this is to provide efficient accumulator maps. For instance, if one wishes to maintain a count of the number of times each key has been seen, they will have to perform some conditional logic on whether this is the first time the key has been seen or not. Normally, this would require a `find` followed by an `insert`, effectively duplicating the search effort on each insertion. When a user calls `map.entry(key)`, the map will search for the key and then yield a variant of the `Entry` enum. If a `Vacant(entry)` is yielded, then the key _was not_ found. In this case the only valid operation is to `insert` a value into the entry. When this is done, the vacant entry is consumed and converted into a mutable reference to the value that was inserted. This allows for further manipulation of the value beyond the lifetime of the search itself. This is useful if complex logic needs to be performed on the value regardless of whether the value was just inserted. If an `Occupied(entry)` is yielded, then the key _was_ found. In this case, the user has several options: they can `get`, `insert` or `remove` the value of the occupied entry. Additionally, they can convert the occupied entry into a mutable reference to its value, providing symmetry to the vacant `insert` case. #### [§](https://doc.rust-lang.org/stable/std/collections/index.html#examples) Examples Here are the two primary ways in which `entry` is used. First, a simple example where the logic performed on the values is trivial. ##### [§](https://doc.rust-lang.org/stable/std/collections/index.html#counting-the-number-of-times-each-character-in-a-string-occurs) Counting the number of times each character in a string occurs use std::collections::btree_map::BTreeMap; let mut count = BTreeMap::new(); let message = "she sells sea shells by the sea shore"; for c in message.chars() { *count.entry(c).or_insert(0) += 1; } assert_eq!(count.get(&'s'), Some(&8)); println!("Number of occurrences of each character"); for (char, count) in &count { println!("{char}: {count}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::btree_map::BTreeMap;%0A++++%0A++++let+mut+count+=+BTreeMap::new();%0A++++let+message+=+%22she+sells+sea+shells+by+the+sea+shore%22;%0A++++%0A++++for+c+in+message.chars()+%7B%0A++++++++*count.entry(c).or_insert(0)+%2B=+1;%0A++++%7D%0A++++%0A++++assert_eq!(count.get(%26%27s%27),+Some(%268));%0A++++%0A++++println!(%22Number+of+occurrences+of+each+character%22);%0A++++for+(char,+count)+in+%26count+%7B%0A++++++++println!(%22%7Bchar%7D:+%7Bcount%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") When the logic to be performed on the value is more complex, we may simply use the `entry` API to ensure that the value is initialized and perform the logic afterwards. ##### [§](https://doc.rust-lang.org/stable/std/collections/index.html#tracking-the-inebriation-of-customers-at-a-bar) Tracking the inebriation of customers at a bar use std::collections::btree_map::BTreeMap; // A client of the bar. They have a blood alcohol level. struct Person { blood_alcohol: f32 } // All the orders made to the bar, by client ID. let orders = vec![1, 2, 1, 2, 3, 4, 1, 2, 2, 3, 4, 1, 1, 1]; // Our clients. let mut blood_alcohol = BTreeMap::new(); for id in orders { // If this is the first time we've seen this customer, initialize them // with no blood alcohol. Otherwise, just retrieve them. let person = blood_alcohol.entry(id).or_insert(Person { blood_alcohol: 0.0 }); // Reduce their blood alcohol level. It takes time to order and drink a beer! person.blood_alcohol *= 0.9; // Check if they're sober enough to have another beer. if person.blood_alcohol > 0.3 { // Too drunk... for now. println!("Sorry {id}, I have to cut you off"); } else { // Have another! person.blood_alcohol += 0.1; } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::btree_map::BTreeMap;%0A++++%0A++++//+A+client+of+the+bar.+They+have+a+blood+alcohol+level.%0A++++struct+Person+%7B+blood_alcohol:+f32+%7D%0A++++%0A++++//+All+the+orders+made+to+the+bar,+by+client+ID.%0A++++let+orders+=+vec!%5B1,+2,+1,+2,+3,+4,+1,+2,+2,+3,+4,+1,+1,+1%5D;%0A++++%0A++++//+Our+clients.%0A++++let+mut+blood_alcohol+=+BTreeMap::new();%0A++++%0A++++for+id+in+orders+%7B%0A++++++++//+If+this+is+the+first+time+we%27ve+seen+this+customer,+initialize+them%0A++++++++//+with+no+blood+alcohol.+Otherwise,+just+retrieve+them.%0A++++++++let+person+=+blood_alcohol.entry(id).or_insert(Person+%7B+blood_alcohol:+0.0+%7D);%0A++++%0A++++++++//+Reduce+their+blood+alcohol+level.+It+takes+time+to+order+and+drink+a+beer!%0A++++++++person.blood_alcohol+*=+0.9;%0A++++%0A++++++++//+Check+if+they%27re+sober+enough+to+have+another+beer.%0A++++++++if+person.blood_alcohol+%3E+0.3+%7B%0A++++++++++++//+Too+drunk...+for+now.%0A++++++++++++println!(%22Sorry+%7Bid%7D,+I+have+to+cut+you+off%22);%0A++++++++%7D+else+%7B%0A++++++++++++//+Have+another!%0A++++++++++++person.blood_alcohol+%2B=+0.1;%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/collections/index.html#insert-and-complex-keys) Insert and complex keys ---------------------------------------------------------------------------------------------------------------- If we have a more complex key, calls to `insert` will not update the value of the key. For example: use std::cmp::Ordering; use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; #[derive(Debug)] struct Foo { a: u32, b: &'static str, } // we will compare `Foo`s by their `a` value only. impl PartialEq for Foo { fn eq(&self, other: &Self) -> bool { self.a == other.a } } impl Eq for Foo {} // we will hash `Foo`s by their `a` value only. impl Hash for Foo { fn hash(&self, h: &mut H) { self.a.hash(h); } } impl PartialOrd for Foo { fn partial_cmp(&self, other: &Self) -> Option { self.a.partial_cmp(&other.a) } } impl Ord for Foo { fn cmp(&self, other: &Self) -> Ordering { self.a.cmp(&other.a) } } let mut map = BTreeMap::new(); map.insert(Foo { a: 1, b: "baz" }, 99); // We already have a Foo with an a of 1, so this will be updating the value. map.insert(Foo { a: 1, b: "xyz" }, 100); // The value has been updated... assert_eq!(map.values().next().unwrap(), &100); // ...but the key hasn't changed. b is still "baz", not "xyz". assert_eq!(map.keys().next().unwrap().b, "baz"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++use+std::collections::BTreeMap;%0A++++use+std::hash::%7BHash,+Hasher%7D;%0A++++%0A++++%23%5Bderive(Debug)%5D%0A++++struct+Foo+%7B%0A++++++++a:+u32,%0A++++++++b:+%26%27static+str,%0A++++%7D%0A++++%0A++++//+we+will+compare+%60Foo%60s+by+their+%60a%60+value+only.%0A++++impl+PartialEq+for+Foo+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B+self.a+==+other.a+%7D%0A++++%7D%0A++++%0A++++impl+Eq+for+Foo+%7B%7D%0A++++%0A++++//+we+will+hash+%60Foo%60s+by+their+%60a%60+value+only.%0A++++impl+Hash+for+Foo+%7B%0A++++++++fn+hash%3CH:+Hasher%3E(%26self,+h:+%26mut+H)+%7B+self.a.hash(h);+%7D%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Foo+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B+self.a.partial_cmp(%26other.a)+%7D%0A++++%7D%0A++++%0A++++impl+Ord+for+Foo+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+Ordering+%7B+self.a.cmp(%26other.a)+%7D%0A++++%7D%0A++++%0A++++let+mut+map+=+BTreeMap::new();%0A++++map.insert(Foo+%7B+a:+1,+b:+%22baz%22+%7D,+99);%0A++++%0A++++//+We+already+have+a+Foo+with+an+a+of+1,+so+this+will+be+updating+the+value.%0A++++map.insert(Foo+%7B+a:+1,+b:+%22xyz%22+%7D,+100);%0A++++%0A++++//+The+value+has+been+updated...%0A++++assert_eq!(map.values().next().unwrap(),+%26100);%0A++++%0A++++//+...but+the+key+hasn%27t+changed.+b+is+still+%22baz%22,+not+%22xyz%22.%0A++++assert_eq!(map.keys().next().unwrap().b,+%22baz%22);%0A%7D&edition=2024 "Run code") Modules[§](https://doc.rust-lang.org/stable/std/collections/index.html#modules) -------------------------------------------------------------------------------- [binary\_heap](https://doc.rust-lang.org/stable/std/collections/binary_heap/index.html "mod std::collections::binary_heap") A priority queue implemented with a binary heap. [btree\_map](https://doc.rust-lang.org/stable/std/collections/btree_map/index.html "mod std::collections::btree_map") An ordered map based on a B-Tree. [btree\_set](https://doc.rust-lang.org/stable/std/collections/btree_set/index.html "mod std::collections::btree_set") An ordered set based on a B-Tree. [hash\_map](https://doc.rust-lang.org/stable/std/collections/hash_map/index.html "mod std::collections::hash_map") A hash map implemented with quadratic probing and SIMD lookup. [hash\_set](https://doc.rust-lang.org/stable/std/collections/hash_set/index.html "mod std::collections::hash_set") A hash set implemented as a `HashMap` where the value is `()`. [linked\_list](https://doc.rust-lang.org/stable/std/collections/linked_list/index.html "mod std::collections::linked_list") A doubly-linked list with owned nodes. [vec\_deque](https://doc.rust-lang.org/stable/std/collections/vec_deque/index.html "mod std::collections::vec_deque") A double-ended queue (deque) implemented with a growable ring buffer. Structs[§](https://doc.rust-lang.org/stable/std/collections/index.html#structs) -------------------------------------------------------------------------------- [BTreeMap](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") An ordered map based on a [B-Tree](https://en.wikipedia.org/wiki/B-tree) . [BTreeSet](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html "struct std::collections::BTreeSet") An ordered set based on a B-Tree. [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") A priority queue implemented with a binary heap. [HashMap](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") A [hash map](https://doc.rust-lang.org/stable/std/collections/index.html#use-a-hashmap-when "mod std::collections") implemented with quadratic probing and SIMD lookup. [HashSet](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html "struct std::collections::HashSet") A [hash set](https://doc.rust-lang.org/stable/std/collections/index.html#use-the-set-variant-of-any-of-these-maps-when "mod std::collections") implemented as a `HashMap` where the value is `()`. [LinkedList](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") A doubly-linked list with owned nodes. [TryReserveError](https://doc.rust-lang.org/stable/std/collections/struct.TryReserveError.html "struct std::collections::TryReserveError") The error type for `try_reserve` methods. [VecDeque](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") A double-ended queue implemented with a growable ring buffer. Enums[§](https://doc.rust-lang.org/stable/std/collections/index.html#enums) ---------------------------------------------------------------------------- [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") Experimental Details of the allocation that caused a `TryReserveError` --- # std::async_iter - Rust [Module async\_iter](https://doc.rust-lang.org/stable/std/async_iter/index.html#) ---------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module async\_iter Copy item path ================================= [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#306) 🔬This is a nightly-only experimental API. (`async_iterator` [#79024](https://github.com/rust-lang/rust/issues/79024) ) Expand description Composable asynchronous iteration. If you’ve found yourself with an asynchronous collection of some kind, and needed to perform an operation on the elements of said collection, you’ll quickly run into ‘async iterators’. Async Iterators are heavily used in idiomatic asynchronous Rust code, so it’s worth becoming familiar with them. Before explaining more, let’s talk about how this module is structured: [§](https://doc.rust-lang.org/stable/std/async_iter/index.html#organization) Organization ----------------------------------------------------------------------------------------- This module is largely organized by type: * [Traits](https://doc.rust-lang.org/stable/std/async_iter/index.html#traits) are the core portion: these traits define what kind of async iterators exist and what you can do with them. The methods of these traits are worth putting some extra study time into. * Functions provide some helpful ways to create some basic async iterators. * Structs are often the return types of the various methods on this module’s traits. You’ll usually want to look at the method that creates the `struct`, rather than the `struct` itself. For more detail about why, see ‘[Implementing Async Iterator](https://doc.rust-lang.org/stable/std/async_iter/index.html#implementing-async-iterator) ’. That’s it! Let’s dig into async iterators. [§](https://doc.rust-lang.org/stable/std/async_iter/index.html#async-iterators) Async Iterators ----------------------------------------------------------------------------------------------- The heart and soul of this module is the [`AsyncIterator`](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html "trait std::async_iter::AsyncIterator") trait. The core of [`AsyncIterator`](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html "trait std::async_iter::AsyncIterator") looks like this: trait AsyncIterator { type Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+core::task::%7BContext,+Poll%7D;%0A++++use+core::pin::Pin;%0A++++trait+AsyncIterator+%7B%0A++++++++type+Item;%0A++++++++fn+poll_next(self:+Pin%3C%26mut+Self%3E,+cx:+%26mut+Context%3C%27_%3E)+-%3E+Poll%3COption%3CSelf::Item%3E%3E;%0A++++%7D%0A%7D&edition=2024 "Run code") Unlike `Iterator`, `AsyncIterator` makes a distinction between the [`poll_next`](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html#tymethod.poll_next "method std::async_iter::AsyncIterator::poll_next") method which is used when implementing an `AsyncIterator`, and a (to-be-implemented) `next` method which is used when consuming an async iterator. Consumers of `AsyncIterator` only need to consider `next`, which when called, returns a future which yields `Option`. The future returned by `next` will yield `Some(Item)` as long as there are elements, and once they’ve all been exhausted, will yield `None` to indicate that iteration is finished. If we’re waiting on something asynchronous to resolve, the future will wait until the async iterator is ready to yield again. Individual async iterators may choose to resume iteration, and so calling `next` again may or may not eventually yield `Some(Item)` again at some point. [`AsyncIterator`](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html "trait std::async_iter::AsyncIterator") ’s full definition includes a number of other methods as well, but they are default methods, built on top of [`poll_next`](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html#tymethod.poll_next "method std::async_iter::AsyncIterator::poll_next") , and so you get them for free. [§](https://doc.rust-lang.org/stable/std/async_iter/index.html#implementing-async-iterator) Implementing Async Iterator ----------------------------------------------------------------------------------------------------------------------- Creating an async iterator of your own involves two steps: creating a `struct` to hold the async iterator’s state, and then implementing [`AsyncIterator`](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html "trait std::async_iter::AsyncIterator") for that `struct`. Let’s make an async iterator named `Counter` which counts from `1` to `5`: #![feature(async_iterator)] // First, the struct: /// An async iterator which counts from one to five struct Counter { count: usize, } // we want our count to start at one, so let's add a new() method to help. // This isn't strictly necessary, but is convenient. Note that we start // `count` at zero, we'll see why in `poll_next()`'s implementation below. impl Counter { fn new() -> Counter { Counter { count: 0 } } } // Then, we implement `AsyncIterator` for our `Counter`: impl AsyncIterator for Counter { // we will be counting with usize type Item = usize; // poll_next() is the only required method fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // Increment our count. This is why we started at zero. self.count += 1; // Check to see if we've finished counting or not. if self.count < 6 { Poll::Ready(Some(self.count)) } else { Poll::Ready(None) } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(async_iterator)%5D%0A%0Afn+main()+%7B%0A++++use+core::async_iter::AsyncIterator;%0A++++use+core::task::%7BContext,+Poll%7D;%0A++++use+core::pin::Pin;%0A++++%0A++++//+First,+the+struct:%0A++++%0A++++///+An+async+iterator+which+counts+from+one+to+five%0A++++struct+Counter+%7B%0A++++++++count:+usize,%0A++++%7D%0A++++%0A++++//+we+want+our+count+to+start+at+one,+so+let%27s+add+a+new()+method+to+help.%0A++++//+This+isn%27t+strictly+necessary,+but+is+convenient.+Note+that+we+start%0A++++//+%60count%60+at+zero,+we%27ll+see+why+in+%60poll_next()%60%27s+implementation+below.%0A++++impl+Counter+%7B%0A++++++++fn+new()+-%3E+Counter+%7B%0A++++++++++++Counter+%7B+count:+0+%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+Then,+we+implement+%60AsyncIterator%60+for+our+%60Counter%60:%0A++++%0A++++impl+AsyncIterator+for+Counter+%7B%0A++++++++//+we+will+be+counting+with+usize%0A++++++++type+Item+=+usize;%0A++++%0A++++++++//+poll_next()+is+the+only+required+method%0A++++++++fn+poll_next(mut+self:+Pin%3C%26mut+Self%3E,+cx:+%26mut+Context%3C%27_%3E)+-%3E+Poll%3COption%3CSelf::Item%3E%3E+%7B%0A++++++++++++//+Increment+our+count.+This+is+why+we+started+at+zero.%0A++++++++++++self.count+%2B=+1;%0A++++%0A++++++++++++//+Check+to+see+if+we%27ve+finished+counting+or+not.%0A++++++++++++if+self.count+%3C+6+%7B%0A++++++++++++++++Poll::Ready(Some(self.count))%0A++++++++++++%7D+else+%7B%0A++++++++++++++++Poll::Ready(None)%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/async_iter/index.html#laziness) Laziness --------------------------------------------------------------------------------- Async iterators are _lazy_. This means that just creating an async iterator doesn’t _do_ a whole lot. Nothing really happens until you call `poll_next`. This is sometimes a source of confusion when creating an async iterator solely for its side effects. The compiler will warn us about this kind of behavior: warning: unused result that must be used: async iterators do nothing unless polled Structs[§](https://doc.rust-lang.org/stable/std/async_iter/index.html#structs) ------------------------------------------------------------------------------- [FromIter](https://doc.rust-lang.org/stable/std/async_iter/struct.FromIter.html "struct std::async_iter::FromIter") Experimental An async iterator that was created from iterator. Traits[§](https://doc.rust-lang.org/stable/std/async_iter/index.html#traits) ----------------------------------------------------------------------------- [AsyncIterator](https://doc.rust-lang.org/stable/std/async_iter/trait.AsyncIterator.html "trait std::async_iter::AsyncIterator") Experimental A trait for dealing with asynchronous iterators. [IntoAsyncIterator](https://doc.rust-lang.org/stable/std/async_iter/trait.IntoAsyncIterator.html "trait std::async_iter::IntoAsyncIterator") Experimental Converts something into an async iterator Functions[§](https://doc.rust-lang.org/stable/std/async_iter/index.html#functions) ----------------------------------------------------------------------------------- [from\_iter](https://doc.rust-lang.org/stable/std/async_iter/fn.from_iter.html "fn std::async_iter::from_iter") Experimental Converts an iterator into an async iterator. --- # assert_eq in std - Rust [assert\_eq](https://doc.rust-lang.org/stable/std/macro.assert_eq.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro assert\_eq Copy item path =============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#42) macro_rules! assert_eq { ($left:expr, $right:expr $(,)?) => { ... }; ($left:expr, $right:expr, $($arg:tt)+) => { ... }; } Expand description Asserts that two expressions are equal to each other (using [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") ). Assertions are always checked in both debug and release builds, and cannot be disabled. See [`debug_assert_eq!`](https://doc.rust-lang.org/stable/std/macro.debug_assert_eq.html "macro std::debug_assert_eq") for assertions that are disabled in release builds by default. On panic, this macro will print the values of the expressions with their debug representations. Like [`assert!`](https://doc.rust-lang.org/stable/std/macro.assert.html "macro std::assert") , this macro has a second form, where a custom panic message can be provided. [§](https://doc.rust-lang.org/stable/std/macro.assert_eq.html#examples) Examples -------------------------------------------------------------------------------- let a = 3; let b = 1 + 2; assert_eq!(a, b); assert_eq!(a, b, "we are testing addition with {} and {}", a, b); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+3;%0A++++let+b+=+1+%2B+2;%0A++++assert_eq!(a,+b);%0A++++%0A++++assert_eq!(a,+b,+%22we+are+testing+addition+with+%7B%7D+and+%7B%7D%22,+a,+b);%0A%7D&edition=2024 "Run code") --- # assert_ne in std - Rust [assert\_ne](https://doc.rust-lang.org/stable/std/macro.assert_ne.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro assert\_ne Copy item path =============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#98) macro_rules! assert_ne { ($left:expr, $right:expr $(,)?) => { ... }; ($left:expr, $right:expr, $($arg:tt)+) => { ... }; } Expand description Asserts that two expressions are not equal to each other (using [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") ). Assertions are always checked in both debug and release builds, and cannot be disabled. See [`debug_assert_ne!`](https://doc.rust-lang.org/stable/std/macro.debug_assert_ne.html "macro std::debug_assert_ne") for assertions that are disabled in release builds by default. On panic, this macro will print the values of the expressions with their debug representations. Like [`assert!`](https://doc.rust-lang.org/stable/std/macro.assert.html "macro std::assert") , this macro has a second form, where a custom panic message can be provided. [§](https://doc.rust-lang.org/stable/std/macro.assert_ne.html#examples) Examples -------------------------------------------------------------------------------- let a = 3; let b = 2; assert_ne!(a, b); assert_ne!(a, b, "we are testing that the values are not equal"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+3;%0A++++let+b+=+2;%0A++++assert_ne!(a,+b);%0A++++%0A++++assert_ne!(a,+b,+%22we+are+testing+that+the+values+are+not+equal%22);%0A%7D&edition=2024 "Run code") --- # assert in std - Rust [assert](https://doc.rust-lang.org/stable/std/macro.assert.html#) ------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro assert Copy item path =========================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1586) macro_rules! assert { ($cond:expr $(,)?) => { ... }; ($cond:expr, $($arg:tt)+) => { ... }; } Expand description Asserts that a boolean expression is `true` at runtime. This will invoke the [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") macro if the provided expression cannot be evaluated to `true` at runtime. [§](https://doc.rust-lang.org/stable/std/macro.assert.html#uses) Uses --------------------------------------------------------------------- Assertions are always checked in both debug and release builds, and cannot be disabled. See [`debug_assert!`](https://doc.rust-lang.org/stable/std/macro.debug_assert.html "macro std::debug_assert") for assertions that are not enabled in release builds by default. Unsafe code may rely on `assert!` to enforce run-time invariants that, if violated could lead to unsafety. Other use-cases of `assert!` include testing and enforcing run-time invariants in safe code (whose violation cannot result in unsafety). [§](https://doc.rust-lang.org/stable/std/macro.assert.html#custom-messages) Custom Messages ------------------------------------------------------------------------------------------- This macro has a second form, where a custom panic message can be provided with or without arguments for formatting. See [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) for syntax for this form. Expressions used as format arguments will only be evaluated if the assertion fails. [§](https://doc.rust-lang.org/stable/std/macro.assert.html#examples) Examples ----------------------------------------------------------------------------- // the panic message for these assertions is the stringified value of the // expression given. assert!(true); fn some_computation() -> bool { // Some expensive computation here true } assert!(some_computation()); // assert with a custom message let x = true; assert!(x, "x wasn't true!"); let a = 3; let b = 27; assert!(a + b == 30, "a = {}, b = {}", a, b); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+the+panic+message+for+these+assertions+is+the+stringified+value+of+the%0A++++//+expression+given.%0A++++assert!(true);%0A++++%0A++++fn+some_computation()+-%3E+bool+%7B%0A++++++++//+Some+expensive+computation+here%0A++++++++true%0A++++%7D%0A++++%0A++++assert!(some_computation());%0A++++%0A++++//+assert+with+a+custom+message%0A++++let+x+=+true;%0A++++assert!(x,+%22x+wasn%27t+true!%22);%0A++++%0A++++let+a+=+3;+let+b+=+27;%0A++++assert!(a+%2B+b+==+30,+%22a+=+%7B%7D,+b+=+%7B%7D%22,+a,+b);%0A%7D&edition=2024 "Run code") --- # debug_assert in std - Rust [debug\_assert](https://doc.rust-lang.org/stable/std/macro.debug_assert.html#) ------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro debug\_assert Copy item path ================================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#292) macro_rules! debug_assert { ($($arg:tt)*) => { ... }; } Expand description Asserts that a boolean expression is `true` at runtime. This will invoke the [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") macro if the provided expression cannot be evaluated to `true` at runtime. Like [`assert!`](https://doc.rust-lang.org/stable/std/macro.assert.html "macro std::assert") , this macro also has a second version, where a custom panic message can be provided. [§](https://doc.rust-lang.org/stable/std/macro.debug_assert.html#uses) Uses --------------------------------------------------------------------------- Unlike [`assert!`](https://doc.rust-lang.org/stable/std/macro.assert.html "macro std::assert") , `debug_assert!` statements are only enabled in non optimized builds by default. An optimized build will not execute `debug_assert!` statements unless `-C debug-assertions` is passed to the compiler. This makes `debug_assert!` useful for checks that are too expensive to be present in a release build but may be helpful during development. The result of expanding `debug_assert!` is always type checked. An unchecked assertion allows a program in an inconsistent state to keep running, which might have unexpected consequences but does not introduce unsafety as long as this only happens in safe code. The performance cost of assertions, however, is not measurable in general. Replacing [`assert!`](https://doc.rust-lang.org/stable/std/macro.assert.html "macro std::assert") with `debug_assert!` is thus only encouraged after thorough profiling, and more importantly, only in safe code! [§](https://doc.rust-lang.org/stable/std/macro.debug_assert.html#examples) Examples ----------------------------------------------------------------------------------- // the panic message for these assertions is the stringified value of the // expression given. debug_assert!(true); fn some_expensive_computation() -> bool { // Some expensive computation here true } debug_assert!(some_expensive_computation()); // assert with a custom message let x = true; debug_assert!(x, "x wasn't true!"); let a = 3; let b = 27; debug_assert!(a + b == 30, "a = {}, b = {}", a, b); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+the+panic+message+for+these+assertions+is+the+stringified+value+of+the%0A++++//+expression+given.%0A++++debug_assert!(true);%0A++++%0A++++fn+some_expensive_computation()+-%3E+bool+%7B%0A++++++++//+Some+expensive+computation+here%0A++++++++true%0A++++%7D%0A++++debug_assert!(some_expensive_computation());%0A++++%0A++++//+assert+with+a+custom+message%0A++++let+x+=+true;%0A++++debug_assert!(x,+%22x+wasn%27t+true!%22);%0A++++%0A++++let+a+=+3;+let+b+=+27;%0A++++debug_assert!(a+%2B+b+==+30,+%22a+=+%7B%7D,+b+=+%7B%7D%22,+a,+b);%0A%7D&edition=2024 "Run code") --- # env in std - Rust [env](https://doc.rust-lang.org/stable/std/macro.env.html#) ------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro env Copy item path ======================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1069) macro_rules! env { ($name:expr $(,)?) => { ... }; ($name:expr, $error_msg:expr $(,)?) => { ... }; } Expand description Inspects an environment variable at compile time. This macro will expand to the value of the named environment variable at compile time, yielding an expression of type `&'static str`. Use [`std::env::var`](https://doc.rust-lang.org/stable/std/env/fn.var.html) instead if you want to read the value at runtime. If the environment variable is not defined, then a compilation error will be emitted. To not emit a compile error, use the [`option_env!`](https://doc.rust-lang.org/stable/std/macro.option_env.html "macro std::option_env") macro instead. A compilation error will also be emitted if the environment variable is not a valid Unicode string. [§](https://doc.rust-lang.org/stable/std/macro.env.html#examples) Examples -------------------------------------------------------------------------- let path: &'static str = env!("PATH"); println!("the $PATH variable at the time of compiling was: {path}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+path:+%26%27static+str+=+env!(%22PATH%22);%0A++++println!(%22the+%24PATH+variable+at+the+time+of+compiling+was:+%7Bpath%7D%22);%0A%7D&edition=2024 "Run code") You can customize the error message by passing a string as the second parameter: [ⓘ](https://doc.rust-lang.org/stable/std/macro.env.html# "This example deliberately fails to compile") let doc: &'static str = env!("documentation", "what's that?!"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+doc:+%26%27static+str+=+env!(%22documentation%22,+%22what%27s+that?!%22);%0A%7D&edition=2024 "Run code") If the `documentation` environment variable is not defined, you’ll get the following error: error: what's that?! --- # std::hash - Rust [Module hash](https://doc.rust-lang.org/stable/std/hash/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module hash Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/hash/mod.rs.html#1-91) Expand description Generic hashing support. This module provides a generic way to compute the [hash](https://en.wikipedia.org/wiki/Hash_function) of a value. Hashes are most commonly used with [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html) and [`HashSet`](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html) . The simplest way to make a type hashable is to use `#[derive(Hash)]`: [§](https://doc.rust-lang.org/stable/std/hash/index.html#examples) Examples --------------------------------------------------------------------------- use std::hash::{DefaultHasher, Hash, Hasher}; #[derive(Hash)] struct Person { id: u32, name: String, phone: u64, } let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777, }; let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777, }; assert!(calculate_hash(&person1) != calculate_hash(&person2)); fn calculate_hash(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::hash::%7BDefaultHasher,+Hash,+Hasher%7D;%0A++++%0A++++%23%5Bderive(Hash)%5D%0A++++struct+Person+%7B%0A++++++++id:+u32,%0A++++++++name:+String,%0A++++++++phone:+u64,%0A++++%7D%0A++++%0A++++let+person1+=+Person+%7B%0A++++++++id:+5,%0A++++++++name:+%22Janet%22.to_string(),%0A++++++++phone:+555_666_7777,%0A++++%7D;%0A++++let+person2+=+Person+%7B%0A++++++++id:+5,%0A++++++++name:+%22Bob%22.to_string(),%0A++++++++phone:+555_666_7777,%0A++++%7D;%0A++++%0A++++assert!(calculate_hash(%26person1)+!=+calculate_hash(%26person2));%0A++++%0A++++fn+calculate_hash%3CT:+Hash%3E(t:+%26T)+-%3E+u64+%7B%0A++++++++let+mut+s+=+DefaultHasher::new();%0A++++++++t.hash(%26mut+s);%0A++++++++s.finish()%0A++++%7D%0A%7D&edition=2024 "Run code") If you need more control over how a value is hashed, you need to implement the [`Hash`](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") trait: use std::hash::{DefaultHasher, Hash, Hasher}; struct Person { id: u32, name: String, phone: u64, } impl Hash for Person { fn hash(&self, state: &mut H) { self.id.hash(state); self.phone.hash(state); } } let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777, }; let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777, }; assert_eq!(calculate_hash(&person1), calculate_hash(&person2)); fn calculate_hash(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::hash::%7BDefaultHasher,+Hash,+Hasher%7D;%0A++++%0A++++struct+Person+%7B%0A++++++++id:+u32,%0A++++%23%5Ballow(dead_code)%5D%0A++++++++name:+String,%0A++++++++phone:+u64,%0A++++%7D%0A++++%0A++++impl+Hash+for+Person+%7B%0A++++++++fn+hash%3CH:+Hasher%3E(%26self,+state:+%26mut+H)+%7B%0A++++++++++++self.id.hash(state);%0A++++++++++++self.phone.hash(state);%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+person1+=+Person+%7B%0A++++++++id:+5,%0A++++++++name:+%22Janet%22.to_string(),%0A++++++++phone:+555_666_7777,%0A++++%7D;%0A++++let+person2+=+Person+%7B%0A++++++++id:+5,%0A++++++++name:+%22Bob%22.to_string(),%0A++++++++phone:+555_666_7777,%0A++++%7D;%0A++++%0A++++assert_eq!(calculate_hash(%26person1),+calculate_hash(%26person2));%0A++++%0A++++fn+calculate_hash%3CT:+Hash%3E(t:+%26T)+-%3E+u64+%7B%0A++++++++let+mut+s+=+DefaultHasher::new();%0A++++++++t.hash(%26mut+s);%0A++++++++s.finish()%0A++++%7D%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/hash/index.html#structs) ------------------------------------------------------------------------- [BuildHasherDefault](https://doc.rust-lang.org/stable/std/hash/struct.BuildHasherDefault.html "struct std::hash::BuildHasherDefault") Used to create a default [`BuildHasher`](https://doc.rust-lang.org/stable/std/hash/trait.BuildHasher.html "trait std::hash::BuildHasher") instance for types that implement [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") and [`Default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") . [DefaultHasher](https://doc.rust-lang.org/stable/std/hash/struct.DefaultHasher.html "struct std::hash::DefaultHasher") The default [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") used by [`RandomState`](https://doc.rust-lang.org/stable/std/hash/struct.RandomState.html "struct std::hash::RandomState") . [RandomState](https://doc.rust-lang.org/stable/std/hash/struct.RandomState.html "struct std::hash::RandomState") `RandomState` is the default state for [`HashMap`](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") types. [SipHasher](https://doc.rust-lang.org/stable/std/hash/struct.SipHasher.html "struct std::hash::SipHasher") Deprecated An implementation of SipHash 2-4. Traits[§](https://doc.rust-lang.org/stable/std/hash/index.html#traits) ----------------------------------------------------------------------- [BuildHasher](https://doc.rust-lang.org/stable/std/hash/trait.BuildHasher.html "trait std::hash::BuildHasher") A trait for creating instances of [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") A hashable type. [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") A trait for hashing an arbitrary stream of bytes. Derive Macros[§](https://doc.rust-lang.org/stable/std/hash/index.html#derives) ------------------------------------------------------------------------------- [Hash](https://doc.rust-lang.org/stable/std/hash/derive.Hash.html "derive std::hash::Hash") Derive macro generating an impl of the trait `Hash`. --- # std::os - Rust [Module os](https://doc.rust-lang.org/stable/std/os/index.html#) ----------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module os Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/os/mod.rs.html#1-198) Expand description OS-specific functionality. Modules[§](https://doc.rust-lang.org/stable/std/os/index.html#modules) ----------------------------------------------------------------------- [darwin](https://doc.rust-lang.org/stable/std/os/darwin/index.html "mod std::os::darwin") Apple Platform-specific extensions to `std` for Darwin / Apple platforms. [fd](https://doc.rust-lang.org/stable/std/os/fd/index.html "mod std::os::fd") Unix or HermitCore or `target_os=trusty` or WASI or `target_os=motor` Owned and borrowed Unix-like file descriptors. [linux](https://doc.rust-lang.org/stable/std/os/linux/index.html "mod std::os::linux") Linux Linux-specific definitions. [raw](https://doc.rust-lang.org/stable/std/os/raw/index.html "mod std::os::raw") Compatibility module for C platform-specific types. Use [`core::ffi`](https://doc.rust-lang.org/stable/core/ffi/index.html "mod core::ffi") instead. [unix](https://doc.rust-lang.org/stable/std/os/unix/index.html "mod std::os::unix") Unix Platform-specific extensions to `std` for Unix platforms. [wasi](https://doc.rust-lang.org/stable/std/os/wasi/index.html "mod std::os::wasi") WASI Platform-specific extensions to `std` for the WebAssembly System Interface (WASI). [wasip2](https://doc.rust-lang.org/stable/std/os/wasip2/index.html "mod std::os::wasip2") WASI and `target_env=p2` Platform-specific extensions to `std` for Preview 2 of the WebAssembly System Interface (WASI). [windows](https://doc.rust-lang.org/stable/std/os/windows/index.html "mod std::os::windows") Windows Platform-specific extensions to `std` for Windows. --- # std::time - Rust [Module time](https://doc.rust-lang.org/stable/std/time/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module time Copy item path ========================== 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#1-727) Expand description Temporal quantification. [§](https://doc.rust-lang.org/stable/std/time/index.html#examples) Examples --------------------------------------------------------------------------- There are multiple ways to create a new [`Duration`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") : let five_seconds = Duration::from_secs(5); assert_eq!(five_seconds, Duration::from_millis(5_000)); assert_eq!(five_seconds, Duration::from_micros(5_000_000)); assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000)); let ten_seconds = Duration::from_secs(10); let seven_nanos = Duration::from_nanos(7); let total = ten_seconds + seven_nanos; assert_eq!(total, Duration::new(10, 7)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++let+five_seconds+=+Duration::from_secs(5);%0A++++assert_eq!(five_seconds,+Duration::from_millis(5_000));%0A++++assert_eq!(five_seconds,+Duration::from_micros(5_000_000));%0A++++assert_eq!(five_seconds,+Duration::from_nanos(5_000_000_000));%0A++++%0A++++let+ten_seconds+=+Duration::from_secs(10);%0A++++let+seven_nanos+=+Duration::from_nanos(7);%0A++++let+total+=+ten_seconds+%2B+seven_nanos;%0A++++assert_eq!(total,+Duration::new(10,+7));%0A%7D&edition=2024 "Run code") Using [`Instant`](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") to calculate how long a function took to run: [ⓘ](https://doc.rust-lang.org/stable/std/time/index.html# "This example is not tested") let now = Instant::now(); // Calling a slow function, it may take a while slow_function(); let elapsed_time = now.elapsed(); println!("Running slow_function() took {} seconds.", elapsed_time.as_secs()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+now+=+Instant::now();%0A++++%0A++++//+Calling+a+slow+function,+it+may+take+a+while%0A++++slow_function();%0A++++%0A++++let+elapsed_time+=+now.elapsed();%0A++++println!(%22Running+slow_function()+took+%7B%7D+seconds.%22,+elapsed_time.as_secs());%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/time/index.html#structs) ------------------------------------------------------------------------- [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") A `Duration` type to represent a span of time, typically used for system timeouts. [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") A measurement of a monotonically nondecreasing clock. Opaque and useful only with [`Duration`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") . [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") A measurement of the system clock, useful for talking to external entities like the file system or other processes. [SystemTimeError](https://doc.rust-lang.org/stable/std/time/struct.SystemTimeError.html "struct std::time::SystemTimeError") An error returned from the `duration_since` and `elapsed` methods on `SystemTime`, used to learn how far in the opposite direction a system time lies. [TryFromFloatSecsError](https://doc.rust-lang.org/stable/std/time/struct.TryFromFloatSecsError.html "struct std::time::TryFromFloatSecsError") An error which can be returned when converting a floating-point value of seconds into a [`Duration`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") . Constants[§](https://doc.rust-lang.org/stable/std/time/index.html#constants) ----------------------------------------------------------------------------- [UNIX\_EPOCH](https://doc.rust-lang.org/stable/std/time/constant.UNIX_EPOCH.html "constant std::time::UNIX_EPOCH") An anchor in time which can be used to create new `SystemTime` instances or learn about where in time a `SystemTime` lies. --- # std::random - Rust [Module random](https://doc.rust-lang.org/stable/std/random/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module random Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/random.rs.html#1-96) 🔬This is a nightly-only experimental API. (`random` [#130703](https://github.com/rust-lang/rust/issues/130703) ) Expand description Random value generation. Structs[§](https://doc.rust-lang.org/stable/std/random/index.html#structs) --------------------------------------------------------------------------- [DefaultRandomSource](https://doc.rust-lang.org/stable/std/random/struct.DefaultRandomSource.html "struct std::random::DefaultRandomSource") Experimental The default random source. Traits[§](https://doc.rust-lang.org/stable/std/random/index.html#traits) ------------------------------------------------------------------------- [Distribution](https://doc.rust-lang.org/stable/std/random/trait.Distribution.html "trait std::random::Distribution") Experimental A trait representing a distribution of random values for a type. [RandomSource](https://doc.rust-lang.org/stable/std/random/trait.RandomSource.html "trait std::random::RandomSource") Experimental A source of randomness. Functions[§](https://doc.rust-lang.org/stable/std/random/index.html#functions) ------------------------------------------------------------------------------- [random](https://doc.rust-lang.org/stable/std/random/fn.random.html "fn std::random::random") Experimental Generates a random value from a distribution, using the default random source. --- # file in std - Rust [file](https://doc.rust-lang.org/stable/std/macro.file.html#) -------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro file Copy item path ========================= 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1254) macro_rules! file { () => { ... }; } Expand description Expands to the file name in which it was invoked. With [`line!`](https://doc.rust-lang.org/stable/std/macro.line.html "macro std::line") and [`column!`](https://doc.rust-lang.org/stable/std/macro.column.html "macro std::column") , these macros provide debugging information for developers about the location within the source. The expanded expression has type `&'static str`, and the returned file is not the invocation of the `file!` macro itself, but rather the first macro invocation leading up to the invocation of the `file!` macro. The file name is derived from the crate root’s source path passed to the Rust compiler and the sequence the compiler takes to get from the crate root to the module containing `file!`, modified by any flags passed to the Rust compiler (e.g. `--remap-path-prefix`). If the crate’s source path is relative, the initial base directory will be the working directory of the Rust compiler. For example, if the source path passed to the compiler is `./src/lib.rs` which has a `mod foo;` with a source path of `src/foo/mod.rs`, then calling `file!` inside `mod foo;` will return `./src/foo/mod.rs`. Future compiler options might make further changes to the behavior of `file!`, including potentially making it entirely empty. Code (e.g. test libraries) relying on `file!` producing an openable file path would be incompatible with such options, and might wish to recommend not using those options. [§](https://doc.rust-lang.org/stable/std/macro.file.html#examples) Examples --------------------------------------------------------------------------- let this_file = file!(); println!("defined in file: {this_file}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+this_file+=+file!();%0A++++println!(%22defined+in+file:+%7Bthis_file%7D%22);%0A%7D&edition=2024 "Run code") --- # std::slice - Rust [Module slice](https://doc.rust-lang.org/stable/std/slice/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module slice Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#223) Expand description Utilities for the slice primitive type. _[See also the slice primitive type](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive slice") ._ Most of the structs in this module are iterator types which can only be created using a certain function. For example, `slice.iter()` yields an [`Iter`](https://doc.rust-lang.org/stable/std/slice/struct.Iter.html "struct std::slice::Iter") . A few functions are provided to create a slice from a value reference or from a raw pointer. Structs[§](https://doc.rust-lang.org/stable/std/slice/index.html#structs) -------------------------------------------------------------------------- [ChunkBy](https://doc.rust-lang.org/stable/std/slice/struct.ChunkBy.html "struct std::slice::ChunkBy") An iterator over slice in (non-overlapping) chunks separated by a predicate. [ChunkByMut](https://doc.rust-lang.org/stable/std/slice/struct.ChunkByMut.html "struct std::slice::ChunkByMut") An iterator over slice in (non-overlapping) mutable chunks separated by a predicate. [Chunks](https://doc.rust-lang.org/stable/std/slice/struct.Chunks.html "struct std::slice::Chunks") An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a time), starting at the beginning of the slice. [ChunksExact](https://doc.rust-lang.org/stable/std/slice/struct.ChunksExact.html "struct std::slice::ChunksExact") An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a time), starting at the beginning of the slice. [ChunksExactMut](https://doc.rust-lang.org/stable/std/slice/struct.ChunksExactMut.html "struct std::slice::ChunksExactMut") An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` elements at a time), starting at the beginning of the slice. [ChunksMut](https://doc.rust-lang.org/stable/std/slice/struct.ChunksMut.html "struct std::slice::ChunksMut") An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` elements at a time), starting at the beginning of the slice. [EscapeAscii](https://doc.rust-lang.org/stable/std/slice/struct.EscapeAscii.html "struct std::slice::EscapeAscii") An iterator over the escaped version of a byte slice. [Iter](https://doc.rust-lang.org/stable/std/slice/struct.Iter.html "struct std::slice::Iter") Immutable slice iterator [IterMut](https://doc.rust-lang.org/stable/std/slice/struct.IterMut.html "struct std::slice::IterMut") Mutable slice iterator. [RChunks](https://doc.rust-lang.org/stable/std/slice/struct.RChunks.html "struct std::slice::RChunks") An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a time), starting at the end of the slice. [RChunksExact](https://doc.rust-lang.org/stable/std/slice/struct.RChunksExact.html "struct std::slice::RChunksExact") An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a time), starting at the end of the slice. [RChunksExactMut](https://doc.rust-lang.org/stable/std/slice/struct.RChunksExactMut.html "struct std::slice::RChunksExactMut") An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` elements at a time), starting at the end of the slice. [RChunksMut](https://doc.rust-lang.org/stable/std/slice/struct.RChunksMut.html "struct std::slice::RChunksMut") An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` elements at a time), starting at the end of the slice. [RSplit](https://doc.rust-lang.org/stable/std/slice/struct.RSplit.html "struct std::slice::RSplit") An iterator over subslices separated by elements that match a predicate function, starting from the end of the slice. [RSplitMut](https://doc.rust-lang.org/stable/std/slice/struct.RSplitMut.html "struct std::slice::RSplitMut") An iterator over the subslices of the vector which are separated by elements that match `pred`, starting from the end of the slice. [RSplitN](https://doc.rust-lang.org/stable/std/slice/struct.RSplitN.html "struct std::slice::RSplitN") An iterator over subslices separated by elements that match a predicate function, limited to a given number of splits, starting from the end of the slice. [RSplitNMut](https://doc.rust-lang.org/stable/std/slice/struct.RSplitNMut.html "struct std::slice::RSplitNMut") An iterator over subslices separated by elements that match a predicate function, limited to a given number of splits, starting from the end of the slice. [Split](https://doc.rust-lang.org/stable/std/slice/struct.Split.html "struct std::slice::Split") An iterator over subslices separated by elements that match a predicate function. [SplitInclusive](https://doc.rust-lang.org/stable/std/slice/struct.SplitInclusive.html "struct std::slice::SplitInclusive") An iterator over subslices separated by elements that match a predicate function. Unlike `Split`, it contains the matched part as a terminator of the subslice. [SplitInclusiveMut](https://doc.rust-lang.org/stable/std/slice/struct.SplitInclusiveMut.html "struct std::slice::SplitInclusiveMut") An iterator over the mutable subslices of the vector which are separated by elements that match `pred`. Unlike `SplitMut`, it contains the matched parts in the ends of the subslices. [SplitMut](https://doc.rust-lang.org/stable/std/slice/struct.SplitMut.html "struct std::slice::SplitMut") An iterator over the mutable subslices of the vector which are separated by elements that match `pred`. [SplitN](https://doc.rust-lang.org/stable/std/slice/struct.SplitN.html "struct std::slice::SplitN") An iterator over subslices separated by elements that match a predicate function, limited to a given number of splits. [SplitNMut](https://doc.rust-lang.org/stable/std/slice/struct.SplitNMut.html "struct std::slice::SplitNMut") An iterator over subslices separated by elements that match a predicate function, limited to a given number of splits. [Windows](https://doc.rust-lang.org/stable/std/slice/struct.Windows.html "struct std::slice::Windows") An iterator over overlapping subslices of length `size`. [ArrayWindows](https://doc.rust-lang.org/stable/std/slice/struct.ArrayWindows.html "struct std::slice::ArrayWindows") Experimental A windowed iterator over a slice in overlapping chunks (`N` elements at a time), starting at the beginning of the slice Enums[§](https://doc.rust-lang.org/stable/std/slice/index.html#enums) ---------------------------------------------------------------------- [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") The error type returned by [`get_disjoint_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_disjoint_mut "method slice::get_disjoint_mut") . Traits[§](https://doc.rust-lang.org/stable/std/slice/index.html#traits) ------------------------------------------------------------------------ [SliceIndex](https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html "trait std::slice::SliceIndex") A helper trait used for indexing operations. [Concat](https://doc.rust-lang.org/stable/std/slice/trait.Concat.html "trait std::slice::Concat") Experimental Helper trait for [`[T]::concat`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.concat "method slice::concat") . [Join](https://doc.rust-lang.org/stable/std/slice/trait.Join.html "trait std::slice::Join") Experimental Helper trait for [`[T]::join`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.join "method slice::join") Functions[§](https://doc.rust-lang.org/stable/std/slice/index.html#functions) ------------------------------------------------------------------------------ [from\_mut](https://doc.rust-lang.org/stable/std/slice/fn.from_mut.html "fn std::slice::from_mut") Converts a reference to T into a slice of length 1 (without copying). [from\_raw\_parts](https://doc.rust-lang.org/stable/std/slice/fn.from_raw_parts.html "fn std::slice::from_raw_parts") ⚠ Forms a slice from a pointer and a length. [from\_raw\_parts\_mut](https://doc.rust-lang.org/stable/std/slice/fn.from_raw_parts_mut.html "fn std::slice::from_raw_parts_mut") ⚠ Performs the same functionality as [`from_raw_parts`](https://doc.rust-lang.org/stable/std/slice/fn.from_raw_parts.html "fn std::slice::from_raw_parts") , except that a mutable slice is returned. [from\_ref](https://doc.rust-lang.org/stable/std/slice/fn.from_ref.html "fn std::slice::from_ref") Converts a reference to T into a slice of length 1 (without copying). [from\_mut\_ptr\_range](https://doc.rust-lang.org/stable/std/slice/fn.from_mut_ptr_range.html "fn std::slice::from_mut_ptr_range") ⚠Experimental Forms a mutable slice from a pointer range. [from\_ptr\_range](https://doc.rust-lang.org/stable/std/slice/fn.from_ptr_range.html "fn std::slice::from_ptr_range") ⚠Experimental Forms a slice from a pointer range. [range](https://doc.rust-lang.org/stable/std/slice/fn.range.html "fn std::slice::range") Experimental Performs bounds checking of a range. [try\_range](https://doc.rust-lang.org/stable/std/slice/fn.try_range.html "fn std::slice::try_range") Experimental Performs bounds checking of a range without panicking. --- # std::alloc - Rust [Module alloc](https://doc.rust-lang.org/stable/std/alloc/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module alloc Copy item path =========================== 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/std/alloc.rs.html#1-438) Expand description Memory allocation APIs. In a given program, the standard library has one “global” memory allocator that is used for example by `Box` and `Vec`. Currently the default global allocator is unspecified. Libraries, however, like `cdylib`s and `staticlib`s are guaranteed to use the [`System`](https://doc.rust-lang.org/stable/std/alloc/struct.System.html "struct std::alloc::System") by default. [§](https://doc.rust-lang.org/stable/std/alloc/index.html#the-global_allocator-attribute) The `#[global_allocator]` attribute ----------------------------------------------------------------------------------------------------------------------------- This attribute allows configuring the choice of global allocator. You can use this to implement a completely custom global allocator to route all default allocation requests to a custom object. use std::alloc::{GlobalAlloc, System, Layout}; struct MyAllocator; unsafe impl GlobalAlloc for MyAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { unsafe { System.alloc(layout) } } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe { System.dealloc(ptr, layout) } } } #[global_allocator] static GLOBAL: MyAllocator = MyAllocator; fn main() { // This `Vec` will allocate memory through `GLOBAL` above let mut v = Vec::new(); v.push(1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::alloc::%7BGlobalAlloc,+System,+Layout%7D;%0A%0Astruct+MyAllocator;%0A%0Aunsafe+impl+GlobalAlloc+for+MyAllocator+%7B%0A++++unsafe+fn+alloc(%26self,+layout:+Layout)+-%3E+*mut+u8+%7B%0A++++++++unsafe+%7B+System.alloc(layout)+%7D%0A++++%7D%0A%0A++++unsafe+fn+dealloc(%26self,+ptr:+*mut+u8,+layout:+Layout)+%7B%0A++++++++unsafe+%7B+System.dealloc(ptr,+layout)+%7D%0A++++%7D%0A%7D%0A%0A%23%5Bglobal_allocator%5D%0Astatic+GLOBAL:+MyAllocator+=+MyAllocator;%0A%0Afn+main()+%7B%0A++++//+This+%60Vec%60+will+allocate+memory+through+%60GLOBAL%60+above%0A++++let+mut+v+=+Vec::new();%0A++++v.push(1);%0A%7D&edition=2024 "Run code") The attribute is used on a `static` item whose type implements the [`GlobalAlloc`](https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html "trait std::alloc::GlobalAlloc") trait. This type can be provided by an external library: [ⓘ](https://doc.rust-lang.org/stable/std/alloc/index.html# "This example is not tested") use jemallocator::Jemalloc; #[global_allocator] static GLOBAL: Jemalloc = Jemalloc; fn main() {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+jemallocator::Jemalloc;%0A%0A%23%5Bglobal_allocator%5D%0Astatic+GLOBAL:+Jemalloc+=+Jemalloc;%0A%0Afn+main()+%7B%7D&edition=2024 "Run code") The `#[global_allocator]` can only be used once in a crate or its recursive dependencies. Structs[§](https://doc.rust-lang.org/stable/std/alloc/index.html#structs) -------------------------------------------------------------------------- [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") Layout of a block of memory. [LayoutError](https://doc.rust-lang.org/stable/std/alloc/struct.LayoutError.html "struct std::alloc::LayoutError") The `LayoutError` is returned when the parameters given to `Layout::from_size_align` or some other `Layout` constructor do not satisfy its documented constraints. [System](https://doc.rust-lang.org/stable/std/alloc/struct.System.html "struct std::alloc::System") The default memory allocator provided by the operating system. [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") Experimental The `AllocError` error indicates an allocation failure that may be due to resource exhaustion or to something wrong when combining the given input arguments with this allocator. [Global](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") Experimental The global memory allocator. Traits[§](https://doc.rust-lang.org/stable/std/alloc/index.html#traits) ------------------------------------------------------------------------ [GlobalAlloc](https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html "trait std::alloc::GlobalAlloc") A memory allocator that can be registered as the standard library’s default through the `#[global_allocator]` attribute. [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") Experimental An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of data described via [`Layout`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") . Functions[§](https://doc.rust-lang.org/stable/std/alloc/index.html#functions) ------------------------------------------------------------------------------ [alloc](https://doc.rust-lang.org/stable/std/alloc/fn.alloc.html "fn std::alloc::alloc") ⚠ Allocates memory with the global allocator. [alloc\_zeroed](https://doc.rust-lang.org/stable/std/alloc/fn.alloc_zeroed.html "fn std::alloc::alloc_zeroed") ⚠ Allocates zero-initialized memory with the global allocator. [dealloc](https://doc.rust-lang.org/stable/std/alloc/fn.dealloc.html "fn std::alloc::dealloc") ⚠ Deallocates memory with the global allocator. [handle\_alloc\_error](https://doc.rust-lang.org/stable/std/alloc/fn.handle_alloc_error.html "fn std::alloc::handle_alloc_error") Signals a memory allocation error. [realloc](https://doc.rust-lang.org/stable/std/alloc/fn.realloc.html "fn std::alloc::realloc") ⚠ Reallocates memory with the global allocator. [set\_alloc\_error\_hook](https://doc.rust-lang.org/stable/std/alloc/fn.set_alloc_error_hook.html "fn std::alloc::set_alloc_error_hook") Experimental Registers a custom allocation error hook, replacing any that was previously registered. [take\_alloc\_error\_hook](https://doc.rust-lang.org/stable/std/alloc/fn.take_alloc_error_hook.html "fn std::alloc::take_alloc_error_hook") Experimental Unregisters the current allocation error hook, returning it. Type Aliases[§](https://doc.rust-lang.org/stable/std/alloc/index.html#types) ----------------------------------------------------------------------------- [LayoutErr](https://doc.rust-lang.org/stable/std/alloc/type.LayoutErr.html "type std::alloc::LayoutErr") Deprecated --- # std::string - Rust [Module string](https://doc.rust-lang.org/stable/std/string/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module string Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#225) Expand description A UTF-8–encoded, growable string. This module contains the [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") type, the [`ToString`](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") trait for converting to strings, and several error types that may result from working with [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") s. [§](https://doc.rust-lang.org/stable/std/string/index.html#examples) Examples ----------------------------------------------------------------------------- There are multiple ways to create a new [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") from a string literal: let s = "Hello".to_string(); let s = String::from("world"); let s: String = "also this".into(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+s+=+%22Hello%22.to_string();%0A++++%0A++++let+s+=+String::from(%22world%22);%0A++++let+s:+String+=+%22also+this%22.into();%0A%7D&edition=2024 "Run code") You can create a new [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") from an existing one by concatenating with `+`: let s = "Hello".to_string(); let message = s + " world!"; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+s+=+%22Hello%22.to_string();%0A++++%0A++++let+message+=+s+%2B+%22+world!%22;%0A%7D&edition=2024 "Run code") If you have a vector of valid UTF-8 bytes, you can make a [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") out of it. You can do the reverse too. let sparkle_heart = vec![240, 159, 146, 150]; // We know these bytes are valid, so we'll use `unwrap()`. let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); assert_eq!("💖", sparkle_heart); let bytes = sparkle_heart.into_bytes(); assert_eq!(bytes, [240, 159, 146, 150]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+sparkle_heart+=+vec!%5B240,+159,+146,+150%5D;%0A++++%0A++++//+We+know+these+bytes+are+valid,+so+we%27ll+use+%60unwrap()%60.%0A++++let+sparkle_heart+=+String::from_utf8(sparkle_heart).unwrap();%0A++++%0A++++assert_eq!(%22%F0%9F%92%96%22,+sparkle_heart);%0A++++%0A++++let+bytes+=+sparkle_heart.into_bytes();%0A++++%0A++++assert_eq!(bytes,+%5B240,+159,+146,+150%5D);%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/string/index.html#structs) --------------------------------------------------------------------------- [Drain](https://doc.rust-lang.org/stable/std/string/struct.Drain.html "struct std::string::Drain") A draining iterator for `String`. [FromUtf8Error](https://doc.rust-lang.org/stable/std/string/struct.FromUtf8Error.html "struct std::string::FromUtf8Error") A possible error value when converting a `String` from a UTF-8 byte vector. [FromUtf16Error](https://doc.rust-lang.org/stable/std/string/struct.FromUtf16Error.html "struct std::string::FromUtf16Error") A possible error value when converting a `String` from a UTF-16 byte slice. [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") A UTF-8–encoded, growable string. [IntoChars](https://doc.rust-lang.org/stable/std/string/struct.IntoChars.html "struct std::string::IntoChars") Experimental An iterator over the [`char`](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") s of a string. Traits[§](https://doc.rust-lang.org/stable/std/string/index.html#traits) ------------------------------------------------------------------------- [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") A trait for converting a value to a `String`. Type Aliases[§](https://doc.rust-lang.org/stable/std/string/index.html#types) ------------------------------------------------------------------------------ [ParseError](https://doc.rust-lang.org/stable/std/string/type.ParseError.html "type std::string::ParseError") A type alias for [`Infallible`](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "convert::Infallible") . --- # eprint in std - Rust [eprint](https://doc.rust-lang.org/stable/std/macro.eprint.html#) ------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro eprint Copy item path =========================== 1.19.0 · [Source](https://doc.rust-lang.org/stable/src/std/macros.rs.html#178-182) macro_rules! eprint { ($($arg:tt)*) => { ... }; } Expand description Prints to the standard error. Equivalent to the [`print!`](https://doc.rust-lang.org/stable/std/macro.print.html "macro std::print") macro, except that output goes to [`io::stderr`](https://doc.rust-lang.org/stable/std/io/fn.stderr.html "fn std::io::stderr") instead of [`io::stdout`](https://doc.rust-lang.org/stable/std/io/fn.stdout.html "fn std::io::stdout") . See [`print!`](https://doc.rust-lang.org/stable/std/macro.print.html "macro std::print") for example usage. Use `eprint!` only for error and progress messages. Use `print!` instead for the primary output of your program. See the formatting documentation in [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html "mod std::fmt") for details of the macro argument syntax. [§](https://doc.rust-lang.org/stable/std/macro.eprint.html#panics) Panics ------------------------------------------------------------------------- Panics if writing to `io::stderr` fails. Writing to non-blocking stderr can cause an error, which will lead this macro to panic. [§](https://doc.rust-lang.org/stable/std/macro.eprint.html#examples) Examples ----------------------------------------------------------------------------- eprint!("Error: Could not complete task"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++eprint!(%22Error:+Could+not+complete+task%22);%0A%7D&edition=2024 "Run code") --- # eprintln in std - Rust [eprintln](https://doc.rust-lang.org/stable/std/macro.eprintln.html#) ---------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro eprintln Copy item path ============================= 1.19.0 · [Source](https://doc.rust-lang.org/stable/src/std/macros.rs.html#216-223) macro_rules! eprintln { () => { ... }; ($($arg:tt)*) => { ... }; } Expand description Prints to the standard error, with a newline. Equivalent to the [`println!`](https://doc.rust-lang.org/stable/std/macro.println.html "macro std::println") macro, except that output goes to [`io::stderr`](https://doc.rust-lang.org/stable/std/io/fn.stderr.html "fn std::io::stderr") instead of [`io::stdout`](https://doc.rust-lang.org/stable/std/io/fn.stdout.html "fn std::io::stdout") . See [`println!`](https://doc.rust-lang.org/stable/std/macro.println.html "macro std::println") for example usage. Use `eprintln!` only for error and progress messages. Use `println!` instead for the primary output of your program. See the formatting documentation in [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html "mod std::fmt") for details of the macro argument syntax. [§](https://doc.rust-lang.org/stable/std/macro.eprintln.html#panics) Panics --------------------------------------------------------------------------- Panics if writing to `io::stderr` fails. Writing to non-blocking stderr can cause an error, which will lead this macro to panic. [§](https://doc.rust-lang.org/stable/std/macro.eprintln.html#examples) Examples ------------------------------------------------------------------------------- eprintln!("Error: Could not complete task"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++eprintln!(%22Error:+Could+not+complete+task%22);%0A%7D&edition=2024 "Run code") --- # std::future - Rust [Module future](https://doc.rust-lang.org/stable/std/future/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module future Copy item path ============================ 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#343) Expand description Asynchronous basic functionality. Please see the fundamental [`async`](https://doc.rust-lang.org/stable/std/keyword.async.html) and [`await`](https://doc.rust-lang.org/stable/std/keyword.await.html) keywords and the [async book](https://rust-lang.github.io/async-book/) for more information on asynchronous programming in Rust. Macros[§](https://doc.rust-lang.org/stable/std/future/index.html#macros) ------------------------------------------------------------------------- [join](https://doc.rust-lang.org/stable/std/future/macro.join.html "macro std::future::join") Experimental Polls multiple futures simultaneously, returning a tuple of all results once complete. Structs[§](https://doc.rust-lang.org/stable/std/future/index.html#structs) --------------------------------------------------------------------------- [Pending](https://doc.rust-lang.org/stable/std/future/struct.Pending.html "struct std::future::Pending") Creates a future which never resolves, representing a computation that never finishes. [PollFn](https://doc.rust-lang.org/stable/std/future/struct.PollFn.html "struct std::future::PollFn") A Future that wraps a function returning [`Poll`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") . [Ready](https://doc.rust-lang.org/stable/std/future/struct.Ready.html "struct std::future::Ready") A future that is immediately ready with a value. Traits[§](https://doc.rust-lang.org/stable/std/future/index.html#traits) ------------------------------------------------------------------------- [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") A future represents an asynchronous computation, commonly obtained by use of [`async`](https://doc.rust-lang.org/stable/std/keyword.async.html) . [IntoFuture](https://doc.rust-lang.org/stable/std/future/trait.IntoFuture.html "trait std::future::IntoFuture") Conversion into a `Future`. [AsyncDrop](https://doc.rust-lang.org/stable/std/future/trait.AsyncDrop.html "trait std::future::AsyncDrop") Experimental Async version of Drop trait. Functions[§](https://doc.rust-lang.org/stable/std/future/index.html#functions) ------------------------------------------------------------------------------- [pending](https://doc.rust-lang.org/stable/std/future/fn.pending.html "fn std::future::pending") Creates a future which never resolves, representing a computation that never finishes. [poll\_fn](https://doc.rust-lang.org/stable/std/future/fn.poll_fn.html "fn std::future::poll_fn") Creates a future that wraps a function returning [`Poll`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") . [ready](https://doc.rust-lang.org/stable/std/future/fn.ready.html "fn std::future::ready") Creates a future that is immediately ready with a value. [async\_drop\_in\_place](https://doc.rust-lang.org/stable/std/future/fn.async_drop_in_place.html "fn std::future::async_drop_in_place") ⚠Experimental Async drop. --- # std::rc - Rust [Module rc](https://doc.rust-lang.org/stable/std/rc/index.html#) ----------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module rc Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#222) Expand description Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’. The type [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") provides shared ownership of a value of type `T`, allocated in the heap. Invoking [`clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone "method std::clone::Clone::clone") on [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") produces a new pointer to the same allocation in the heap. When the last [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") pointer to a given allocation is destroyed, the value stored in that allocation (often referred to as “inner value”) is also dropped. Shared references in Rust disallow mutation by default, and [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") is no exception: you cannot generally obtain a mutable reference to something inside an [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") . If you need mutability, put a [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") or [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") inside the [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") ; see [an example of mutability inside an `Rc`](https://doc.rust-lang.org/stable/std/cell/index.html#introducing-mutability-inside-of-something-immutable "mod std::cell") . [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") uses non-atomic reference counting. This means that overhead is very low, but an [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") cannot be sent between threads, and consequently [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") does not implement [`Send`](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") . As a result, the Rust compiler will check _at compile time_ that you are not sending [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") s between threads. If you need multi-threaded, atomic reference counting, use [`sync::Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") . The [`downgrade`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.downgrade "associated function std::rc::Rc::downgrade") method can be used to create a non-owning [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") pointer. A [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") pointer can be [`upgrade`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html#method.upgrade "method std::rc::Weak::upgrade") d to an [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") , but this will return [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if the value stored in the allocation has already been dropped. In other words, `Weak` pointers do not keep the value inside the allocation alive; however, they _do_ keep the allocation (the backing store for the inner value) alive. A cycle between [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") pointers will never be deallocated. For this reason, [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") is used to break cycles. For example, a tree could have strong [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") pointers from parent nodes to children, and [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") pointers from children back to their parents. `Rc` automatically dereferences to `T` (via the [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") trait), so you can call `T`’s methods on a value of type [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") . To avoid name clashes with `T`’s methods, the methods of [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") itself are associated functions, called using [fully qualified syntax](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name) : use std::rc::Rc; let my_rc = Rc::new(()); let my_weak = Rc::downgrade(&my_rc); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::rc::Rc;%0A++++%0A++++let+my_rc+=+Rc::new(());%0A++++let+my_weak+=+Rc::downgrade(%26my_rc);%0A%7D&edition=2024 "Run code") `Rc`’s implementations of traits like `Clone` may also be called using fully qualified syntax. Some people prefer to use fully qualified syntax, while others prefer using method-call syntax. use std::rc::Rc; let rc = Rc::new(()); // Method-call syntax let rc2 = rc.clone(); // Fully qualified syntax let rc3 = Rc::clone(&rc); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::rc::Rc;%0A++++%0A++++let+rc+=+Rc::new(());%0A++++//+Method-call+syntax%0A++++let+rc2+=+rc.clone();%0A++++//+Fully+qualified+syntax%0A++++let+rc3+=+Rc::clone(%26rc);%0A%7D&edition=2024 "Run code") [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") does not auto-dereference to `T`, because the inner value may have already been dropped. [§](https://doc.rust-lang.org/stable/std/rc/index.html#cloning-references) Cloning references --------------------------------------------------------------------------------------------- Creating a new reference to the same allocation as an existing reference counted pointer is done using the `Clone` trait implemented for [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") and [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") . use std::rc::Rc; let foo = Rc::new(vec![1.0, 2.0, 3.0]); // The two syntaxes below are equivalent. let a = foo.clone(); let b = Rc::clone(&foo); // a and b both point to the same memory location as foo. [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::rc::Rc;%0A++++%0A++++let+foo+=+Rc::new(vec!%5B1.0,+2.0,+3.0%5D);%0A++++//+The+two+syntaxes+below+are+equivalent.%0A++++let+a+=+foo.clone();%0A++++let+b+=+Rc::clone(%26foo);%0A%7D&edition=2024 "Run code") The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly the meaning of the code. In the example above, this syntax makes it easier to see that this code is creating a new reference rather than copying the whole content of foo. [§](https://doc.rust-lang.org/stable/std/rc/index.html#examples) Examples ------------------------------------------------------------------------- Consider a scenario where a set of `Gadget`s are owned by a given `Owner`. We want to have our `Gadget`s point to their `Owner`. We can’t do this with unique ownership, because more than one gadget may belong to the same `Owner`. [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") allows us to share an `Owner` between multiple `Gadget`s, and have the `Owner` remain allocated as long as any `Gadget` points at it. use std::rc::Rc; struct Owner { name: String, // ...other fields } struct Gadget { id: i32, owner: Rc, // ...other fields } fn main() { // Create a reference-counted `Owner`. let gadget_owner: Rc = Rc::new( Owner { name: "Gadget Man".to_string(), } ); // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc` // gives us a new pointer to the same `Owner` allocation, incrementing // the reference count in the process. let gadget1 = Gadget { id: 1, owner: Rc::clone(&gadget_owner), }; let gadget2 = Gadget { id: 2, owner: Rc::clone(&gadget_owner), }; // Dispose of our local variable `gadget_owner`. drop(gadget_owner); // Despite dropping `gadget_owner`, we're still able to print out the name // of the `Owner` of the `Gadget`s. This is because we've only dropped a // single `Rc`, not the `Owner` it points to. As long as there are // other `Rc` pointing at the same `Owner` allocation, it will remain // live. The field projection `gadget1.owner.name` works because // `Rc` automatically dereferences to `Owner`. println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name); println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name); // At the end of the function, `gadget1` and `gadget2` are destroyed, and // with them the last counted references to our `Owner`. Gadget Man now // gets destroyed as well. } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::rc::Rc;%0A%0Astruct+Owner+%7B%0A++++name:+String,%0A++++//+...other+fields%0A%7D%0A%0Astruct+Gadget+%7B%0A++++id:+i32,%0A++++owner:+Rc%3COwner%3E,%0A++++//+...other+fields%0A%7D%0A%0Afn+main()+%7B%0A++++//+Create+a+reference-counted+%60Owner%60.%0A++++let+gadget_owner:+Rc%3COwner%3E+=+Rc::new(%0A++++++++Owner+%7B%0A++++++++++++name:+%22Gadget+Man%22.to_string(),%0A++++++++%7D%0A++++);%0A%0A++++//+Create+%60Gadget%60s+belonging+to+%60gadget_owner%60.+Cloning+the+%60Rc%3COwner%3E%60%0A++++//+gives+us+a+new+pointer+to+the+same+%60Owner%60+allocation,+incrementing%0A++++//+the+reference+count+in+the+process.%0A++++let+gadget1+=+Gadget+%7B%0A++++++++id:+1,%0A++++++++owner:+Rc::clone(%26gadget_owner),%0A++++%7D;%0A++++let+gadget2+=+Gadget+%7B%0A++++++++id:+2,%0A++++++++owner:+Rc::clone(%26gadget_owner),%0A++++%7D;%0A%0A++++//+Dispose+of+our+local+variable+%60gadget_owner%60.%0A++++drop(gadget_owner);%0A%0A++++//+Despite+dropping+%60gadget_owner%60,+we%27re+still+able+to+print+out+the+name%0A++++//+of+the+%60Owner%60+of+the+%60Gadget%60s.+This+is+because+we%27ve+only+dropped+a%0A++++//+single+%60Rc%3COwner%3E%60,+not+the+%60Owner%60+it+points+to.+As+long+as+there+are%0A++++//+other+%60Rc%3COwner%3E%60+pointing+at+the+same+%60Owner%60+allocation,+it+will+remain%0A++++//+live.+The+field+projection+%60gadget1.owner.name%60+works+because%0A++++//+%60Rc%3COwner%3E%60+automatically+dereferences+to+%60Owner%60.%0A++++println!(%22Gadget+%7B%7D+owned+by+%7B%7D%22,+gadget1.id,+gadget1.owner.name);%0A++++println!(%22Gadget+%7B%7D+owned+by+%7B%7D%22,+gadget2.id,+gadget2.owner.name);%0A%0A++++//+At+the+end+of+the+function,+%60gadget1%60+and+%60gadget2%60+are+destroyed,+and%0A++++//+with+them+the+last+counted+references+to+our+%60Owner%60.+Gadget+Man+now%0A++++//+gets+destroyed+as+well.%0A%7D&edition=2024 "Run code") If our requirements change, and we also need to be able to traverse from `Owner` to `Gadget`, we will run into problems. An [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") pointer from `Owner` to `Gadget` introduces a cycle. This means that their reference counts can never reach 0, and the allocation will never be destroyed: a memory leak. In order to get around this, we can use [`Weak`](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") pointers. Rust actually makes it somewhat difficult to produce this loop in the first place. In order to end up with two values that point at each other, one of them needs to be mutable. This is difficult because [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") enforces memory safety by only giving out shared references to the value it wraps, and these don’t allow direct mutation. We need to wrap the part of the value we wish to mutate in a [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") , which provides _interior mutability_: a method to achieve mutability through a shared reference. [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") enforces Rust’s borrowing rules at runtime. use std::rc::Rc; use std::rc::Weak; use std::cell::RefCell; struct Owner { name: String, gadgets: RefCell>>, // ...other fields } struct Gadget { id: i32, owner: Rc, // ...other fields } fn main() { // Create a reference-counted `Owner`. Note that we've put the `Owner`'s // vector of `Gadget`s inside a `RefCell` so that we can mutate it through // a shared reference. let gadget_owner: Rc = Rc::new( Owner { name: "Gadget Man".to_string(), gadgets: RefCell::new(vec![]), } ); // Create `Gadget`s belonging to `gadget_owner`, as before. let gadget1 = Rc::new( Gadget { id: 1, owner: Rc::clone(&gadget_owner), } ); let gadget2 = Rc::new( Gadget { id: 2, owner: Rc::clone(&gadget_owner), } ); // Add the `Gadget`s to their `Owner`. { let mut gadgets = gadget_owner.gadgets.borrow_mut(); gadgets.push(Rc::downgrade(&gadget1)); gadgets.push(Rc::downgrade(&gadget2)); // `RefCell` dynamic borrow ends here. } // Iterate over our `Gadget`s, printing their details out. for gadget_weak in gadget_owner.gadgets.borrow().iter() { // `gadget_weak` is a `Weak`. Since `Weak` pointers can't // guarantee the allocation still exists, we need to call // `upgrade`, which returns an `Option>`. // // In this case we know the allocation still exists, so we simply // `unwrap` the `Option`. In a more complicated program, you might // need graceful error handling for a `None` result. let gadget = gadget_weak.upgrade().unwrap(); println!("Gadget {} owned by {}", gadget.id, gadget.owner.name); } // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2` // are destroyed. There are now no strong (`Rc`) pointers to the // gadgets, so they are destroyed. This zeroes the reference count on // Gadget Man, so he gets destroyed as well. } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::rc::Rc;%0Ause+std::rc::Weak;%0Ause+std::cell::RefCell;%0A%0Astruct+Owner+%7B%0A++++name:+String,%0A++++gadgets:+RefCell%3CVec%3CWeak%3CGadget%3E%3E%3E,%0A++++//+...other+fields%0A%7D%0A%0Astruct+Gadget+%7B%0A++++id:+i32,%0A++++owner:+Rc%3COwner%3E,%0A++++//+...other+fields%0A%7D%0A%0Afn+main()+%7B%0A++++//+Create+a+reference-counted+%60Owner%60.+Note+that+we%27ve+put+the+%60Owner%60%27s%0A++++//+vector+of+%60Gadget%60s+inside+a+%60RefCell%60+so+that+we+can+mutate+it+through%0A++++//+a+shared+reference.%0A++++let+gadget_owner:+Rc%3COwner%3E+=+Rc::new(%0A++++++++Owner+%7B%0A++++++++++++name:+%22Gadget+Man%22.to_string(),%0A++++++++++++gadgets:+RefCell::new(vec!%5B%5D),%0A++++++++%7D%0A++++);%0A%0A++++//+Create+%60Gadget%60s+belonging+to+%60gadget_owner%60,+as+before.%0A++++let+gadget1+=+Rc::new(%0A++++++++Gadget+%7B%0A++++++++++++id:+1,%0A++++++++++++owner:+Rc::clone(%26gadget_owner),%0A++++++++%7D%0A++++);%0A++++let+gadget2+=+Rc::new(%0A++++++++Gadget+%7B%0A++++++++++++id:+2,%0A++++++++++++owner:+Rc::clone(%26gadget_owner),%0A++++++++%7D%0A++++);%0A%0A++++//+Add+the+%60Gadget%60s+to+their+%60Owner%60.%0A++++%7B%0A++++++++let+mut+gadgets+=+gadget_owner.gadgets.borrow_mut();%0A++++++++gadgets.push(Rc::downgrade(%26gadget1));%0A++++++++gadgets.push(Rc::downgrade(%26gadget2));%0A%0A++++++++//+%60RefCell%60+dynamic+borrow+ends+here.%0A++++%7D%0A%0A++++//+Iterate+over+our+%60Gadget%60s,+printing+their+details+out.%0A++++for+gadget_weak+in+gadget_owner.gadgets.borrow().iter()+%7B%0A%0A++++++++//+%60gadget_weak%60+is+a+%60Weak%3CGadget%3E%60.+Since+%60Weak%60+pointers+can%27t%0A++++++++//+guarantee+the+allocation+still+exists,+we+need+to+call%0A++++++++//+%60upgrade%60,+which+returns+an+%60Option%3CRc%3CGadget%3E%3E%60.%0A++++++++//%0A++++++++//+In+this+case+we+know+the+allocation+still+exists,+so+we+simply%0A++++++++//+%60unwrap%60+the+%60Option%60.+In+a+more+complicated+program,+you+might%0A++++++++//+need+graceful+error+handling+for+a+%60None%60+result.%0A%0A++++++++let+gadget+=+gadget_weak.upgrade().unwrap();%0A++++++++println!(%22Gadget+%7B%7D+owned+by+%7B%7D%22,+gadget.id,+gadget.owner.name);%0A++++%7D%0A%0A++++//+At+the+end+of+the+function,+%60gadget_owner%60,+%60gadget1%60,+and+%60gadget2%60%0A++++//+are+destroyed.+There+are+now+no+strong+(%60Rc%60)+pointers+to+the%0A++++//+gadgets,+so+they+are+destroyed.+This+zeroes+the+reference+count+on%0A++++//+Gadget+Man,+so+he+gets+destroyed+as+well.%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/rc/index.html#structs) ----------------------------------------------------------------------- [Rc](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’. [Weak](https://doc.rust-lang.org/stable/std/rc/struct.Weak.html "struct std::rc::Weak") `Weak` is a version of [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") that holds a non-owning reference to the managed allocation. [UniqueRc](https://doc.rust-lang.org/stable/std/rc/struct.UniqueRc.html "struct std::rc::UniqueRc") Experimental A uniquely owned [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") . --- # std::f32 - Rust [Module f32](https://doc.rust-lang.org/stable/std/f32/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module f32 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/num/f32.rs.html#1-1263) Expand description Constants for the `f32` single-precision floating point type. _[See also the `f32` primitive type](https://doc.rust-lang.org/stable/std/primitive.f32.html "primitive f32") ._ Mathematically significant numbers are provided in the `consts` sub-module. For the constants defined directly in this module (as distinct from those defined in the `consts` sub-module), new code should instead use the associated constants defined directly on the `f32` type. Modules[§](https://doc.rust-lang.org/stable/std/f32/index.html#modules) ------------------------------------------------------------------------ [consts](https://doc.rust-lang.org/stable/std/f32/consts/index.html "mod std::f32::consts") Basic mathematical constants. Constants[§](https://doc.rust-lang.org/stable/std/f32/index.html#constants) ---------------------------------------------------------------------------- [DIGITS](https://doc.rust-lang.org/stable/std/f32/constant.DIGITS.html "constant std::f32::DIGITS") Deprecation planned Approximate number of significant digits in base 10. Use [`f32::DIGITS`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.DIGITS "associated constant f32::DIGITS") instead. [EPSILON](https://doc.rust-lang.org/stable/std/f32/constant.EPSILON.html "constant std::f32::EPSILON") Deprecation planned [Machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value for `f32`. Use [`f32::EPSILON`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.EPSILON "associated constant f32::EPSILON") instead. [INFINITY](https://doc.rust-lang.org/stable/std/f32/constant.INFINITY.html "constant std::f32::INFINITY") Deprecation planned Infinity (∞). Use [`f32::INFINITY`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.INFINITY "associated constant f32::INFINITY") instead. [MANTISSA\_DIGITS](https://doc.rust-lang.org/stable/std/f32/constant.MANTISSA_DIGITS.html "constant std::f32::MANTISSA_DIGITS") Deprecation planned Number of significant digits in base 2. Use [`f32::MANTISSA_DIGITS`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MANTISSA_DIGITS "associated constant f32::MANTISSA_DIGITS") instead. [MAX](https://doc.rust-lang.org/stable/std/f32/constant.MAX.html "constant std::f32::MAX") Deprecation planned Largest finite `f32` value. Use [`f32::MAX`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MAX "associated constant f32::MAX") instead. [MAX\_10\_EXP](https://doc.rust-lang.org/stable/std/f32/constant.MAX_10_EXP.html "constant std::f32::MAX_10_EXP") Deprecation planned Maximum possible power of 10 exponent. Use [`f32::MAX_10_EXP`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MAX_10_EXP "associated constant f32::MAX_10_EXP") instead. [MAX\_EXP](https://doc.rust-lang.org/stable/std/f32/constant.MAX_EXP.html "constant std::f32::MAX_EXP") Deprecation planned Maximum possible power of 2 exponent. Use [`f32::MAX_EXP`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MAX_EXP "associated constant f32::MAX_EXP") instead. [MIN](https://doc.rust-lang.org/stable/std/f32/constant.MIN.html "constant std::f32::MIN") Deprecation planned Smallest finite `f32` value. Use [`f32::MIN`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MIN "associated constant f32::MIN") instead. [MIN\_10\_EXP](https://doc.rust-lang.org/stable/std/f32/constant.MIN_10_EXP.html "constant std::f32::MIN_10_EXP") Deprecation planned Minimum possible normal power of 10 exponent. Use [`f32::MIN_10_EXP`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MIN_10_EXP "associated constant f32::MIN_10_EXP") instead. [MIN\_EXP](https://doc.rust-lang.org/stable/std/f32/constant.MIN_EXP.html "constant std::f32::MIN_EXP") Deprecation planned One greater than the minimum possible normal power of 2 exponent. Use [`f32::MIN_EXP`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MIN_EXP "associated constant f32::MIN_EXP") instead. [MIN\_POSITIVE](https://doc.rust-lang.org/stable/std/f32/constant.MIN_POSITIVE.html "constant std::f32::MIN_POSITIVE") Deprecation planned Smallest positive normal `f32` value. Use [`f32::MIN_POSITIVE`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MIN_POSITIVE "associated constant f32::MIN_POSITIVE") instead. [NAN](https://doc.rust-lang.org/stable/std/f32/constant.NAN.html "constant std::f32::NAN") Deprecation planned Not a Number (NaN). Use [`f32::NAN`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.NAN "associated constant f32::NAN") instead. [NEG\_INFINITY](https://doc.rust-lang.org/stable/std/f32/constant.NEG_INFINITY.html "constant std::f32::NEG_INFINITY") Deprecation planned Negative infinity (−∞). Use [`f32::NEG_INFINITY`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.NEG_INFINITY "associated constant f32::NEG_INFINITY") instead. [RADIX](https://doc.rust-lang.org/stable/std/f32/constant.RADIX.html "constant std::f32::RADIX") Deprecation planned The radix or base of the internal representation of `f32`. Use [`f32::RADIX`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.RADIX "associated constant f32::RADIX") instead. --- # std::f64 - Rust [Module f64](https://doc.rust-lang.org/stable/std/f64/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module f64 Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/num/f64.rs.html#1-1263) Expand description Constants for the `f64` double-precision floating point type. _[See also the `f64` primitive type](https://doc.rust-lang.org/stable/std/primitive.f64.html "primitive f64") ._ Mathematically significant numbers are provided in the `consts` sub-module. For the constants defined directly in this module (as distinct from those defined in the `consts` sub-module), new code should instead use the associated constants defined directly on the `f64` type. Modules[§](https://doc.rust-lang.org/stable/std/f64/index.html#modules) ------------------------------------------------------------------------ [consts](https://doc.rust-lang.org/stable/std/f64/consts/index.html "mod std::f64::consts") Basic mathematical constants. Constants[§](https://doc.rust-lang.org/stable/std/f64/index.html#constants) ---------------------------------------------------------------------------- [DIGITS](https://doc.rust-lang.org/stable/std/f64/constant.DIGITS.html "constant std::f64::DIGITS") Deprecation planned Approximate number of significant digits in base 10. Use [`f64::DIGITS`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.DIGITS "associated constant f64::DIGITS") instead. [EPSILON](https://doc.rust-lang.org/stable/std/f64/constant.EPSILON.html "constant std::f64::EPSILON") Deprecation planned [Machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value for `f64`. Use [`f64::EPSILON`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.EPSILON "associated constant f64::EPSILON") instead. [INFINITY](https://doc.rust-lang.org/stable/std/f64/constant.INFINITY.html "constant std::f64::INFINITY") Deprecation planned Infinity (∞). Use [`f64::INFINITY`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.INFINITY "associated constant f64::INFINITY") instead. [MANTISSA\_DIGITS](https://doc.rust-lang.org/stable/std/f64/constant.MANTISSA_DIGITS.html "constant std::f64::MANTISSA_DIGITS") Deprecation planned Number of significant digits in base 2. Use [`f64::MANTISSA_DIGITS`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MANTISSA_DIGITS "associated constant f64::MANTISSA_DIGITS") instead. [MAX](https://doc.rust-lang.org/stable/std/f64/constant.MAX.html "constant std::f64::MAX") Deprecation planned Largest finite `f64` value. Use [`f64::MAX`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MAX "associated constant f64::MAX") instead. [MAX\_10\_EXP](https://doc.rust-lang.org/stable/std/f64/constant.MAX_10_EXP.html "constant std::f64::MAX_10_EXP") Deprecation planned Maximum possible power of 10 exponent. Use [`f64::MAX_10_EXP`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MAX_10_EXP "associated constant f64::MAX_10_EXP") instead. [MAX\_EXP](https://doc.rust-lang.org/stable/std/f64/constant.MAX_EXP.html "constant std::f64::MAX_EXP") Deprecation planned Maximum possible power of 2 exponent. Use [`f64::MAX_EXP`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MAX_EXP "associated constant f64::MAX_EXP") instead. [MIN](https://doc.rust-lang.org/stable/std/f64/constant.MIN.html "constant std::f64::MIN") Deprecation planned Smallest finite `f64` value. Use [`f64::MIN`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MIN "associated constant f64::MIN") instead. [MIN\_10\_EXP](https://doc.rust-lang.org/stable/std/f64/constant.MIN_10_EXP.html "constant std::f64::MIN_10_EXP") Deprecation planned Minimum possible normal power of 10 exponent. Use [`f64::MIN_10_EXP`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MIN_10_EXP "associated constant f64::MIN_10_EXP") instead. [MIN\_EXP](https://doc.rust-lang.org/stable/std/f64/constant.MIN_EXP.html "constant std::f64::MIN_EXP") Deprecation planned One greater than the minimum possible normal power of 2 exponent. Use [`f64::MIN_EXP`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MIN_EXP "associated constant f64::MIN_EXP") instead. [MIN\_POSITIVE](https://doc.rust-lang.org/stable/std/f64/constant.MIN_POSITIVE.html "constant std::f64::MIN_POSITIVE") Deprecation planned Smallest positive normal `f64` value. Use [`f64::MIN_POSITIVE`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MIN_POSITIVE "associated constant f64::MIN_POSITIVE") instead. [NAN](https://doc.rust-lang.org/stable/std/f64/constant.NAN.html "constant std::f64::NAN") Deprecation planned Not a Number (NaN). Use [`f64::NAN`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.NAN "associated constant f64::NAN") instead. [NEG\_INFINITY](https://doc.rust-lang.org/stable/std/f64/constant.NEG_INFINITY.html "constant std::f64::NEG_INFINITY") Deprecation planned Negative infinity (−∞). Use [`f64::NEG_INFINITY`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.NEG_INFINITY "associated constant f64::NEG_INFINITY") instead. [RADIX](https://doc.rust-lang.org/stable/std/f64/constant.RADIX.html "constant std::f64::RADIX") Deprecation planned The radix or base of the internal representation of `f64`. Use [`f64::RADIX`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.RADIX "associated constant f64::RADIX") instead. --- # std::vec - Rust [Module vec](https://doc.rust-lang.org/stable/std/vec/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module vec Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#230) Expand description A contiguous growable array type with heap-allocated contents, written `Vec`. Vectors have _O_(1) indexing, amortized _O_(1) push (to the end) and _O_(1) pop (from the end). Vectors ensure they never allocate more than `isize::MAX` bytes. [§](https://doc.rust-lang.org/stable/std/vec/index.html#examples) Examples -------------------------------------------------------------------------- You can explicitly create a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") with [`Vec::new`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.new "associated function std::vec::Vec::new") : let v: Vec = Vec::new(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v:+Vec%3Ci32%3E+=+Vec::new();%0A%7D&edition=2024 "Run code") …or by using the [`vec!`](https://doc.rust-lang.org/stable/std/macro.vec.html "macro std::vec") macro: let v: Vec = vec![]; let v = vec![1, 2, 3, 4, 5]; let v = vec![0; 10]; // ten zeroes [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v:+Vec%3Ci32%3E+=+vec!%5B%5D;%0A++++%0A++++let+v+=+vec!%5B1,+2,+3,+4,+5%5D;%0A++++%0A++++let+v+=+vec!%5B0;+10%5D;%0A%7D&edition=2024 "Run code") You can [`push`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.push "method std::vec::Vec::push") values onto the end of a vector (which will grow the vector as needed): let mut v = vec![1, 2]; v.push(3); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+v+=+vec!%5B1,+2%5D;%0A++++%0A++++v.push(3);%0A%7D&edition=2024 "Run code") Popping values works in much the same way: let mut v = vec![1, 2]; let two = v.pop(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+v+=+vec!%5B1,+2%5D;%0A++++%0A++++let+two+=+v.pop();%0A%7D&edition=2024 "Run code") Vectors also support indexing (through the [`Index`](https://doc.rust-lang.org/stable/std/ops/trait.Index.html "trait std::ops::Index") and [`IndexMut`](https://doc.rust-lang.org/stable/std/ops/trait.IndexMut.html "trait std::ops::IndexMut") traits): let mut v = vec![1, 2, 3]; let three = v[2]; v[1] = v[1] + 5; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+v+=+vec!%5B1,+2,+3%5D;%0A++++let+three+=+v%5B2%5D;%0A++++v%5B1%5D+=+v%5B1%5D+%2B+5;%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/vec/index.html#memory-layout) Memory layout ------------------------------------------------------------------------------------ When the type is non-zero-sized and the capacity is nonzero, [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") uses the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator for its allocation. It is valid to convert both ways between such a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") and a raw pointer allocated with the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator, provided that the [`Layout`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") used with the allocator is correct for a sequence of `capacity` elements of the type, and the first `len` values pointed to by the raw pointer are valid. More precisely, a `ptr: *mut T` that has been allocated with the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator with [`Layout::array::(capacity)`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.array "associated function std::alloc::Layout::array") may be converted into a vec using [`Vec::::from_raw_parts(ptr, len, capacity)`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.from_raw_parts "associated function std::vec::Vec::from_raw_parts") . Conversely, the memory backing a `value: *mut T` obtained from [`Vec::::as_mut_ptr`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_mut_ptr "method std::vec::Vec::as_mut_ptr") may be deallocated using the [`Global`](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") allocator with the same layout. For zero-sized types (ZSTs), or when the capacity is zero, the `Vec` pointer must be non-null and sufficiently aligned. The recommended way to build a `Vec` of ZSTs if [`vec!`](https://doc.rust-lang.org/stable/std/macro.vec.html "macro std::vec") cannot be used is to use [`ptr::NonNull::dangling`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.dangling "associated function std::ptr::NonNull::dangling") . Structs[§](https://doc.rust-lang.org/stable/std/vec/index.html#structs) ------------------------------------------------------------------------ [Drain](https://doc.rust-lang.org/stable/std/vec/struct.Drain.html "struct std::vec::Drain") A draining iterator for `Vec`. [ExtractIf](https://doc.rust-lang.org/stable/std/vec/struct.ExtractIf.html "struct std::vec::ExtractIf") An iterator which uses a closure to determine if an element should be removed. [IntoIter](https://doc.rust-lang.org/stable/std/vec/struct.IntoIter.html "struct std::vec::IntoIter") An iterator that moves out of a vector. [Splice](https://doc.rust-lang.org/stable/std/vec/struct.Splice.html "struct std::vec::Splice") A splicing iterator for `Vec`. [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") A contiguous growable array type, written as `Vec`, short for ‘vector’. [PeekMut](https://doc.rust-lang.org/stable/std/vec/struct.PeekMut.html "struct std::vec::PeekMut") Experimental Structure wrapping a mutable reference to the last item in a `Vec`. --- # format_args in std - Rust [format\_args](https://doc.rust-lang.org/stable/std/macro.format_args.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro format\_args Copy item path ================================= 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#997) macro_rules! format_args { ($fmt:expr) => { ... }; ($fmt:expr, $($args:tt)*) => { ... }; } Expand description 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`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") trait can be passed to `format_args!`, as can any [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementation be passed to a `{:?}` within the formatting string. This macro produces a value of type [`fmt::Arguments`](https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html "struct std::fmt::Arguments") . This value can be passed to the macros within [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) for performing useful redirection. All other formatting macros ([`format!`](https://doc.rust-lang.org/stable/std/macro.format.html) , [`write!`](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") , [`println!`](https://doc.rust-lang.org/stable/std/macro.println.html) , etc) are proxied through this one. `format_args!`, unlike its derived macros, avoids heap allocations. You can use the [`fmt::Arguments`](https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html "struct std::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); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+args+=+format_args!(%22%7B%7D+foo+%7B:?%7D%22,+1,+2);%0A++++let+debug+=+format!(%22%7Bargs:?%7D%22);%0A++++let+display+=+format!(%22%7Bargs%7D%22);%0A++++assert_eq!(%221+foo+2%22,+display);%0A++++assert_eq!(display,+debug);%0A%7D&edition=2024 "Run code") See [the formatting documentation in `std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) for details of the macro argument syntax, and further information. [§](https://doc.rust-lang.org/stable/std/macro.format_args.html#examples) Examples ---------------------------------------------------------------------------------- use std::fmt; let s = fmt::format(format_args!("hello {}", "world")); assert_eq!(s, format!("hello {}", "world")); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::fmt;%0A++++%0A++++let+s+=+fmt::format(format_args!(%22hello+%7B%7D%22,+%22world%22));%0A++++assert_eq!(s,+format!(%22hello+%7B%7D%22,+%22world%22));%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/macro.format_args.html#argument-lifetimes) 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](https://doc.rust-lang.org/stable/reference/destructors.html#temporary-lifetime-extension) 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](https://doc.rust-lang.org/stable/reference/destructors.html#extending-based-on-expressions) . --- # std::sync::atomic - Rust [Module atomic](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#) ------------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) Module atomic Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/mod.rs.html#5) Expand description Atomic types Atomic types provide primitive shared-memory communication between threads, and are the building blocks of other concurrent types. This module defines atomic versions of a select number of primitive types, including [`AtomicBool`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicBool.html "struct std::sync::atomic::AtomicBool") , [`AtomicIsize`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicIsize.html "struct std::sync::atomic::AtomicIsize") , [`AtomicUsize`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html "struct std::sync::atomic::AtomicUsize") , [`AtomicI8`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicI8.html "struct std::sync::atomic::AtomicI8") , [`AtomicU16`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU16.html "struct std::sync::atomic::AtomicU16") , etc. Atomic types present operations that, when used correctly, synchronize updates between threads. Atomic variables are safe to share between threads (they implement [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") ) but they do not themselves provide the mechanism for sharing and follow the [threading model](https://doc.rust-lang.org/stable/std/thread/index.html#the-threading-model) of Rust. The most common way to share an atomic variable is to put it into an [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html) (an atomically-reference-counted shared pointer). Atomic types may be stored in static variables, initialized using the constant initializers like [`AtomicBool::new`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicBool.html#method.new "associated function std::sync::atomic::AtomicBool::new") . Atomic statics are often used for lazy global initialization. ### [§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#memory-model-for-atomic-accesses) Memory model for atomic accesses Rust atomics currently follow the same rules as [C++20 atomics](https://en.cppreference.com/w/cpp/atomic) , specifically the rules from the [`intro.races`](https://timsong-cpp.github.io/cppwp/n4868/intro.multithread#intro.races) section, without the “consume” memory ordering. Since C++ uses an object-based memory model whereas Rust is access-based, a bit of translation work has to be done to apply the C++ rules to Rust: whenever C++ talks about “the value of an object”, we understand that to mean the resulting bytes obtained when doing a read. When the C++ standard talks about “the value of an atomic object”, this refers to the result of doing an atomic load (via the operations provided in this module). A “modification of an atomic object” refers to an atomic store. The end result is _almost_ equivalent to saying that creating a _shared reference_ to one of the Rust atomic types corresponds to creating an `atomic_ref` in C++, with the `atomic_ref` being destroyed when the lifetime of the shared reference ends. The main difference is that Rust permits concurrent atomic and non-atomic reads to the same memory as those cause no issue in the C++ memory model, they are just forbidden in C++ because memory is partitioned into “atomic objects” and “non-atomic objects” (with `atomic_ref` temporarily converting a non-atomic object into an atomic object). The most important aspect of this model is that _data races_ are undefined behavior. A data race is defined as conflicting non-synchronized accesses where at least one of the accesses is non-atomic. Here, accesses are _conflicting_ if they affect overlapping regions of memory and at least one of them is a write. (A `compare_exchange` or `compare_exchange_weak` that does not succeed is not considered a write.) They are _non-synchronized_ if neither of them _happens-before_ the other, according to the happens-before order of the memory model. The other possible cause of undefined behavior in the memory model are mixed-size accesses: Rust inherits the C++ limitation that non-synchronized conflicting atomic accesses may not partially overlap. In other words, every pair of non-synchronized atomic accesses must be either disjoint, access the exact same memory (including using the same access size), or both be reads. Each atomic access takes an [`Ordering`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") which defines how the operation interacts with the happens-before order. These orderings behave the same as the corresponding [C++20 atomic orderings](https://en.cppreference.com/w/cpp/atomic/memory_order) . For more information, see the [nomicon](https://doc.rust-lang.org/stable/nomicon/atomics.html) . use std::sync::atomic::{AtomicU16, AtomicU8, Ordering}; use std::mem::transmute; use std::thread; let atomic = AtomicU16::new(0); thread::scope(|s| { // This is UB: conflicting non-synchronized accesses, at least one of which is non-atomic. s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write }); thread::scope(|s| { // This is fine: the accesses do not conflict (as none of them performs any modification). // In C++ this would be disallowed since creating an `atomic_ref` precludes // further non-atomic accesses, but Rust does not have that limitation. s.spawn(|| atomic.load(Ordering::Relaxed)); // atomic load s.spawn(|| unsafe { atomic.as_ptr().read() }); // non-atomic read }); thread::scope(|s| { // This is fine: `join` synchronizes the code in a way such that the atomic // store happens-before the non-atomic write. let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store handle.join().expect("thread won't panic"); // synchronize s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write }); thread::scope(|s| { // This is UB: non-synchronized conflicting differently-sized atomic accesses. s.spawn(|| atomic.store(1, Ordering::Relaxed)); s.spawn(|| unsafe { let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic); differently_sized.store(2, Ordering::Relaxed); }); }); thread::scope(|s| { // This is fine: `join` synchronizes the code in a way such that // the 1-byte store happens-before the 2-byte store. let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); handle.join().expect("thread won't panic"); s.spawn(|| unsafe { let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic); differently_sized.store(2, Ordering::Relaxed); }); }); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::atomic::%7BAtomicU16,+AtomicU8,+Ordering%7D;%0A++++use+std::mem::transmute;%0A++++use+std::thread;%0A++++%0A++++let+atomic+=+AtomicU16::new(0);%0A++++%0A++++thread::scope(%7Cs%7C+%7B%0A++++++++//+This+is+UB:+conflicting+non-synchronized+accesses,+at+least+one+of+which+is+non-atomic.%0A++++++++s.spawn(%7C%7C+atomic.store(1,+Ordering::Relaxed));+//+atomic+store%0A++++++++s.spawn(%7C%7C+unsafe+%7B+atomic.as_ptr().write(2)+%7D);+//+non-atomic+write%0A++++%7D);%0A++++%0A++++thread::scope(%7Cs%7C+%7B%0A++++++++//+This+is+fine:+the+accesses+do+not+conflict+(as+none+of+them+performs+any+modification).%0A++++++++//+In+C%2B%2B+this+would+be+disallowed+since+creating+an+%60atomic_ref%60+precludes%0A++++++++//+further+non-atomic+accesses,+but+Rust+does+not+have+that+limitation.%0A++++++++s.spawn(%7C%7C+atomic.load(Ordering::Relaxed));+//+atomic+load%0A++++++++s.spawn(%7C%7C+unsafe+%7B+atomic.as_ptr().read()+%7D);+//+non-atomic+read%0A++++%7D);%0A++++%0A++++thread::scope(%7Cs%7C+%7B%0A++++++++//+This+is+fine:+%60join%60+synchronizes+the+code+in+a+way+such+that+the+atomic%0A++++++++//+store+happens-before+the+non-atomic+write.%0A++++++++let+handle+=+s.spawn(%7C%7C+atomic.store(1,+Ordering::Relaxed));+//+atomic+store%0A++++++++handle.join().expect(%22thread+won%27t+panic%22);+//+synchronize%0A++++++++s.spawn(%7C%7C+unsafe+%7B+atomic.as_ptr().write(2)+%7D);+//+non-atomic+write%0A++++%7D);%0A++++%0A++++thread::scope(%7Cs%7C+%7B%0A++++++++//+This+is+UB:+non-synchronized+conflicting+differently-sized+atomic+accesses.%0A++++++++s.spawn(%7C%7C+atomic.store(1,+Ordering::Relaxed));%0A++++++++s.spawn(%7C%7C+unsafe+%7B%0A++++++++++++let+differently_sized+=+transmute::%3C%26AtomicU16,+%26AtomicU8%3E(%26atomic);%0A++++++++++++differently_sized.store(2,+Ordering::Relaxed);%0A++++++++%7D);%0A++++%7D);%0A++++%0A++++thread::scope(%7Cs%7C+%7B%0A++++++++//+This+is+fine:+%60join%60+synchronizes+the+code+in+a+way+such+that%0A++++++++//+the+1-byte+store+happens-before+the+2-byte+store.%0A++++++++let+handle+=+s.spawn(%7C%7C+atomic.store(1,+Ordering::Relaxed));%0A++++++++handle.join().expect(%22thread+won%27t+panic%22);%0A++++++++s.spawn(%7C%7C+unsafe+%7B%0A++++++++++++let+differently_sized+=+transmute::%3C%26AtomicU16,+%26AtomicU8%3E(%26atomic);%0A++++++++++++differently_sized.store(2,+Ordering::Relaxed);%0A++++++++%7D);%0A++++%7D);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#portability) Portability ---------------------------------------------------------------------------------------- All atomic types in this module are guaranteed to be [lock-free](https://en.wikipedia.org/wiki/Non-blocking_algorithm) if they’re available. This means they don’t internally acquire a global mutex. Atomic types and operations are not guaranteed to be wait-free. This means that operations like `fetch_or` may be implemented with a compare-and-swap loop. Atomic operations may be implemented at the instruction layer with larger-size atomics. For example some platforms use 4-byte atomic instructions to implement `AtomicI8`. Note that this emulation should not have an impact on correctness of code, it’s just something to be aware of. The atomic types in this module might not be available on all platforms. The atomic types here are all widely available, however, and can generally be relied upon existing. Some notable exceptions are: * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or `AtomicI64` types. * ARM platforms like `armv5te` that aren’t for Linux only provide `load` and `store` operations, and do not support Compare and Swap (CAS) operations, such as `swap`, `fetch_add`, etc. Additionally on Linux, these CAS operations are implemented via [operating system support](https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt) , which may come with a performance penalty. * ARM targets with `thumbv6m` only provide `load` and `store` operations, and do not support Compare and Swap (CAS) operations, such as `swap`, `fetch_add`, etc. Note that future platforms may be added that also do not have support for some atomic operations. Maximally portable code will want to be careful about which atomic types are used. `AtomicUsize` and `AtomicIsize` are generally the most portable, but even then they’re not available everywhere. For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although `core` does not. The `#[cfg(target_has_atomic)]` attribute can be used to conditionally compile based on the target’s supported bit widths. It is a key-value option set for each supported size, with values “8”, “16”, “32”, “64”, “128”, and “ptr” for pointer-sized atomics. [§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#atomic-accesses-to-read-only-memory) Atomic accesses to read-only memory ---------------------------------------------------------------------------------------------------------------------------------------- In general, _all_ atomic accesses on read-only memory are undefined behavior. For instance, attempting to do a `compare_exchange` that will definitely fail (making it conceptually a read-only operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault on read-only memory. For the purpose of this section, “read-only memory” is defined as memory that is read-only in the underlying target, i.e., the pages are mapped with a read-only flag and any attempt to write will cause a page fault. In particular, an `&u128` reference that points to memory that is read-write mapped is _not_ considered to point to “read-only memory”. In Rust, almost all memory is read-write; the only exceptions are memory created by `const` items or `static` items without interior mutability, and memory that was specifically marked as read-only by the operating system via platform-specific APIs. As an exception from the general rule stated above, “sufficiently small” atomic loads with `Ordering::Relaxed` are implemented in a way that works on read-only memory, and are hence not undefined behavior. The exact size limit for what makes a load “sufficiently small” varies depending on the target: | `target_arch` | Size limit | | --- | --- | | `x86`, `arm`, `loongarch32`, `mips`, `mips32r6`, `powerpc`, `riscv32`, `sparc`, `hexagon` | 4 bytes | | `x86_64`, `aarch64`, `loongarch64`, `mips64`, `mips64r6`, `powerpc64`, `riscv64`, `sparc64`, `s390x` | 8 bytes | Atomics loads that are larger than this limit as well as atomic loads with ordering other than `Relaxed`, as well as _all_ atomic loads on targets not listed in the table, might still be read-only under certain conditions, but that is not a stable guarantee and should not be relied upon. If you need to do an acquire load on read-only memory, you can do a relaxed load followed by an acquire fence instead. [§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#examples) Examples ---------------------------------------------------------------------------------- A simple spinlock: [ⓘ](https://doc.rust-lang.org/stable/std/sync/atomic/index.html# "This example is not tested on wasm") use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::{hint, thread}; fn main() { let spinlock = Arc::new(AtomicUsize::new(1)); let spinlock_clone = Arc::clone(&spinlock); let thread = thread::spawn(move || { spinlock_clone.store(0, Ordering::Release); }); // Wait for the other thread to release the lock while spinlock.load(Ordering::Acquire) != 0 { hint::spin_loop(); } if let Err(panic) = thread.join() { println!("Thread had an error: {panic:?}"); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::sync::Arc;%0Ause+std::sync::atomic::%7BAtomicUsize,+Ordering%7D;%0Ause+std::%7Bhint,+thread%7D;%0A%0Afn+main()+%7B%0A++++let+spinlock+=+Arc::new(AtomicUsize::new(1));%0A%0A++++let+spinlock_clone+=+Arc::clone(%26spinlock);%0A%0A++++let+thread+=+thread::spawn(move+%7C%7C+%7B%0A++++++++spinlock_clone.store(0,+Ordering::Release);%0A++++%7D);%0A%0A++++//+Wait+for+the+other+thread+to+release+the+lock%0A++++while+spinlock.load(Ordering::Acquire)+!=+0+%7B%0A++++++++hint::spin_loop();%0A++++%7D%0A%0A++++if+let+Err(panic)+=+thread.join()+%7B%0A++++++++println!(%22Thread+had+an+error:+%7Bpanic:?%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") Keep a global count of live threads: use std::sync::atomic::{AtomicUsize, Ordering}; static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0); // Note that Relaxed ordering doesn't synchronize anything // except the global thread counter itself. let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed); // Note that this number may not be true at the moment of printing // because some other thread may have changed static value already. println!("live threads: {}", old_thread_count + 1); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::atomic::%7BAtomicUsize,+Ordering%7D;%0A++++%0A++++static+GLOBAL_THREAD_COUNT:+AtomicUsize+=+AtomicUsize::new(0);%0A++++%0A++++//+Note+that+Relaxed+ordering+doesn%27t+synchronize+anything%0A++++//+except+the+global+thread+counter+itself.%0A++++let+old_thread_count+=+GLOBAL_THREAD_COUNT.fetch_add(1,+Ordering::Relaxed);%0A++++//+Note+that+this+number+may+not+be+true+at+the+moment+of+printing%0A++++//+because+some+other+thread+may+have+changed+static+value+already.%0A++++println!(%22live+threads:+%7B%7D%22,+old_thread_count+%2B+1);%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#structs) -------------------------------------------------------------------------------- [AtomicBool](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicBool.html "struct std::sync::atomic::AtomicBool") A boolean type which can be safely shared between threads. [AtomicI8](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicI8.html "struct std::sync::atomic::AtomicI8") An integer type which can be safely shared between threads. [AtomicI16](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicI16.html "struct std::sync::atomic::AtomicI16") An integer type which can be safely shared between threads. [AtomicI32](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicI32.html "struct std::sync::atomic::AtomicI32") An integer type which can be safely shared between threads. [AtomicI64](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicI64.html "struct std::sync::atomic::AtomicI64") An integer type which can be safely shared between threads. [AtomicIsize](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicIsize.html "struct std::sync::atomic::AtomicIsize") An integer type which can be safely shared between threads. [AtomicPtr](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html "struct std::sync::atomic::AtomicPtr") A raw pointer type which can be safely shared between threads. [AtomicU8](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU8.html "struct std::sync::atomic::AtomicU8") An integer type which can be safely shared between threads. [AtomicU16](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU16.html "struct std::sync::atomic::AtomicU16") An integer type which can be safely shared between threads. [AtomicU32](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU32.html "struct std::sync::atomic::AtomicU32") An integer type which can be safely shared between threads. [AtomicU64](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicU64.html "struct std::sync::atomic::AtomicU64") An integer type which can be safely shared between threads. [AtomicUsize](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html "struct std::sync::atomic::AtomicUsize") An integer type which can be safely shared between threads. Enums[§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#enums) ---------------------------------------------------------------------------- [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") Atomic memory orderings Constants[§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#constants) ------------------------------------------------------------------------------------ [ATOMIC\_BOOL\_INIT](https://doc.rust-lang.org/stable/std/sync/atomic/constant.ATOMIC_BOOL_INIT.html "constant std::sync::atomic::ATOMIC_BOOL_INIT") Deprecated An [`AtomicBool`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicBool.html "struct std::sync::atomic::AtomicBool") initialized to `false`. [ATOMIC\_ISIZE\_INIT](https://doc.rust-lang.org/stable/std/sync/atomic/constant.ATOMIC_ISIZE_INIT.html "constant std::sync::atomic::ATOMIC_ISIZE_INIT") Deprecated An [`AtomicIsize`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicIsize.html "struct std::sync::atomic::AtomicIsize") initialized to `0`. [ATOMIC\_USIZE\_INIT](https://doc.rust-lang.org/stable/std/sync/atomic/constant.ATOMIC_USIZE_INIT.html "constant std::sync::atomic::ATOMIC_USIZE_INIT") Deprecated An [`AtomicUsize`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html "struct std::sync::atomic::AtomicUsize") initialized to `0`. Traits[§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#traits) ------------------------------------------------------------------------------ [AtomicPrimitive](https://doc.rust-lang.org/stable/std/sync/atomic/trait.AtomicPrimitive.html "trait std::sync::atomic::AtomicPrimitive") Experimental A marker trait for primitive types which can be modified atomically. Functions[§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#functions) ------------------------------------------------------------------------------------ [compiler\_fence](https://doc.rust-lang.org/stable/std/sync/atomic/fn.compiler_fence.html "fn std::sync::atomic::compiler_fence") A “compiler-only” atomic fence. [fence](https://doc.rust-lang.org/stable/std/sync/atomic/fn.fence.html "fn std::sync::atomic::fence") An atomic fence. [spin\_loop\_hint](https://doc.rust-lang.org/stable/std/sync/atomic/fn.spin_loop_hint.html "fn std::sync::atomic::spin_loop_hint") Deprecated Signals the processor that it is inside a busy-wait spin-loop (“spin lock”). Type Aliases[§](https://doc.rust-lang.org/stable/std/sync/atomic/index.html#types) ----------------------------------------------------------------------------------- [Atomic](https://doc.rust-lang.org/stable/std/sync/atomic/type.Atomic.html "type std::sync::atomic::Atomic") Experimental A memory location which can be safely modified from multiple threads. --- # std::error - Rust [Module error](https://doc.rust-lang.org/stable/std/error/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module error Copy item path =========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/error.rs.html#1-562) Expand description Interfaces for working with Errors. [§](https://doc.rust-lang.org/stable/std/error/index.html#error-handling-in-rust) Error Handling In Rust -------------------------------------------------------------------------------------------------------- The Rust language provides two complementary systems for constructing / representing, reporting, propagating, reacting to, and discarding errors. These responsibilities are collectively known as “error handling.” The components of the first system, the panic runtime and interfaces, are most commonly used to represent bugs that have been detected in your program. The components of the second system, `Result`, the error traits, and user defined types, are used to represent anticipated runtime failure modes of your program. ### [§](https://doc.rust-lang.org/stable/std/error/index.html#the-panic-interfaces) The Panic Interfaces The following are the primary interfaces of the panic system and the responsibilities they cover: * [`panic!`](https://doc.rust-lang.org/stable/std/macro.panic.html "macro std::panic") and [`panic_any`](https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html) (Constructing, Propagated automatically) * [`set_hook`](https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html) , [`take_hook`](https://doc.rust-lang.org/stable/std/panic/fn.take_hook.html) , and [`PanicHookInfo`](https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html) (Reporting) * [`#[panic_handler]`](https://doc.rust-lang.org/nomicon/panic-handler.html) and [`PanicInfo`](https://doc.rust-lang.org/stable/std/panic/type.PanicInfo.html "type std::panic::PanicInfo") (Reporting in no\_std) * [`catch_unwind`](https://doc.rust-lang.org/stable/std/panic/fn.catch_unwind.html) and [`resume_unwind`](https://doc.rust-lang.org/stable/std/panic/fn.resume_unwind.html) (Discarding, Propagating) The following are the primary interfaces of the error system and the responsibilities they cover: * [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") (Propagating, Reacting) * The [`Error`](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") trait (Reporting) * User defined types (Constructing / Representing) * [`match`](https://doc.rust-lang.org/stable/std/keyword.match.html) and [`downcast`](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") (Reacting) * The question mark operator ([`?`](https://doc.rust-lang.org/stable/std/result/index.html#the-question-mark-operator-) ) (Propagating) * The partially stable [`Try`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") traits (Propagating, Constructing) * [`Termination`](https://doc.rust-lang.org/stable/std/process/trait.Termination.html) (Reporting) ### [§](https://doc.rust-lang.org/stable/std/error/index.html#converting-errors-into-panics) Converting Errors into Panics The panic and error systems are not entirely distinct. Often times errors that are anticipated runtime failures in an API might instead represent bugs to a caller. For these situations the standard library provides APIs for constructing panics with an `Error` as its source. * [`Result::unwrap`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap "method std::result::Result::unwrap") * [`Result::expect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.expect "method std::result::Result::expect") These functions are equivalent, they either return the inner value if the `Result` is `Ok` or panic if the `Result` is `Err` printing the inner error as the source. The only difference between them is that with `expect` you provide a panic error message to be printed alongside the source, whereas `unwrap` has a default message indicating only that you unwrapped an `Err`. Of the two, `expect` is generally preferred since its `msg` field allows you to convey your intent and assumptions which makes tracking down the source of a panic easier. `unwrap` on the other hand can still be a good fit in situations where you can trivially show that a piece of code will never panic, such as `"127.0.0.1".parse::().unwrap()` or early prototyping. [§](https://doc.rust-lang.org/stable/std/error/index.html#common-message-styles) Common Message Styles ------------------------------------------------------------------------------------------------------ There are two common styles for how people word `expect` messages. Using the message to present information to users encountering a panic (“expect as error message”) or using the message to present information to developers debugging the panic (“expect as precondition”). In the former case the expect message is used to describe the error that has occurred which is considered a bug. Consider the following example: [ⓘ](https://doc.rust-lang.org/stable/std/error/index.html# "This example panics") // Read environment variable, panic if it is not present let path = std::env::var("IMPORTANT_PATH").unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+Read+environment+variable,+panic+if+it+is+not+present%0A++++let+path+=+std::env::var(%22IMPORTANT_PATH%22).unwrap();%0A%7D&edition=2024 "Run code") In the “expect as error message” style we would use expect to describe that the environment variable was not set when it should have been: [ⓘ](https://doc.rust-lang.org/stable/std/error/index.html# "This example panics") let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` is not set"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+path+=+std::env::var(%22IMPORTANT_PATH%22)%0A++++++++.expect(%22env+variable+%60IMPORTANT_PATH%60+is+not+set%22);%0A%7D&edition=2024 "Run code") In the “expect as precondition” style, we would instead describe the reason we _expect_ the `Result` should be `Ok`. With this style we would prefer to write: [ⓘ](https://doc.rust-lang.org/stable/std/error/index.html# "This example panics") let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+path+=+std::env::var(%22IMPORTANT_PATH%22)%0A++++++++.expect(%22env+variable+%60IMPORTANT_PATH%60+should+be+set+by+%60wrapper_script.sh%60%22);%0A%7D&edition=2024 "Run code") The “expect as error message” style does not work as well with the default output of the std panic hooks, and often ends up repeating information that is already communicated by the source error being unwrapped: thread 'main' panicked at src/main.rs:4:6: env variable `IMPORTANT_PATH` is not set: NotPresent In this example we end up mentioning that an env variable is not set, followed by our source message that says the env is not present, the only additional information we’re communicating is the name of the environment variable being checked. The “expect as precondition” style instead focuses on source code readability, making it easier to understand what must have gone wrong in situations where panics are being used to represent bugs exclusively. Also, by framing our expect in terms of what “SHOULD” have happened to prevent the source error, we end up introducing new information that is independent from our source error. thread 'main' panicked at src/main.rs:4:6: env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`: NotPresent In this example we are communicating not only the name of the environment variable that should have been set, but also an explanation for why it should have been set, and we let the source error display as a clear contradiction to our expectation. **Hint**: If you’re having trouble remembering how to phrase expect-as-precondition style error messages remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”. Structs[§](https://doc.rust-lang.org/stable/std/error/index.html#structs) -------------------------------------------------------------------------- [Report](https://doc.rust-lang.org/stable/std/error/struct.Report.html "struct std::error::Report") Experimental An error reporter that prints an error and its sources. [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") Experimental `Request` supports generic, type-driven access to data. Its use is currently restricted to the standard library in cases where trait authors wish to allow trait implementors to share generic information across trait boundaries. The motivating and prototypical use case is `core::error::Error` which would otherwise require a method per concrete type (eg. `std::backtrace::Backtrace` instance that implementors want to expose to users). Traits[§](https://doc.rust-lang.org/stable/std/error/index.html#traits) ------------------------------------------------------------------------ [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") `Error` is a trait representing the basic expectations for error values, i.e., values of type `E` in [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . Functions[§](https://doc.rust-lang.org/stable/std/error/index.html#functions) ------------------------------------------------------------------------------ [request\_ref](https://doc.rust-lang.org/stable/std/error/fn.request_ref.html "fn std::error::request_ref") Experimental Requests a reference of type `T` from the given `impl Error`. [request\_value](https://doc.rust-lang.org/stable/std/error/fn.request_value.html "fn std::error::request_value") Experimental Requests a value of type `T` from the given `impl Error`. --- # std::task - Rust [Module task](https://doc.rust-lang.org/stable/std/task/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module task Copy item path ========================== 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/std/lib.rs.html#645) Expand description Types and Traits for working with asynchronous tasks. Macros[§](https://doc.rust-lang.org/stable/std/task/index.html#macros) ----------------------------------------------------------------------- [ready](https://doc.rust-lang.org/stable/std/task/macro.ready.html "macro std::task::ready") Extracts the successful type of a [`Poll`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") . Structs[§](https://doc.rust-lang.org/stable/std/task/index.html#structs) ------------------------------------------------------------------------- [Context](https://doc.rust-lang.org/stable/std/task/struct.Context.html "struct std::task::Context") The context of an asynchronous task. [RawWaker](https://doc.rust-lang.org/stable/std/task/struct.RawWaker.html "struct std::task::RawWaker") A `RawWaker` allows the implementor of a task executor to create a [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") or a [`LocalWaker`](https://doc.rust-lang.org/stable/std/task/struct.LocalWaker.html "struct std::task::LocalWaker") which provides customized wakeup behavior. [RawWakerVTable](https://doc.rust-lang.org/stable/std/task/struct.RawWakerVTable.html "struct std::task::RawWakerVTable") A virtual function pointer table (vtable) that specifies the behavior of a [`RawWaker`](https://doc.rust-lang.org/stable/std/task/struct.RawWaker.html "struct std::task::RawWaker") . [Waker](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") A `Waker` is a handle for waking up a task by notifying its executor that it is ready to be run. [ContextBuilder](https://doc.rust-lang.org/stable/std/task/struct.ContextBuilder.html "struct std::task::ContextBuilder") Experimental A Builder used to construct a `Context` instance with support for `LocalWaker`. [LocalWaker](https://doc.rust-lang.org/stable/std/task/struct.LocalWaker.html "struct std::task::LocalWaker") Experimental A `LocalWaker` is analogous to a [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") , but it does not implement [`Send`](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") or [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") . Enums[§](https://doc.rust-lang.org/stable/std/task/index.html#enums) --------------------------------------------------------------------- [Poll](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") Indicates whether a value is available or if the current task has been scheduled to receive a wakeup instead. Traits[§](https://doc.rust-lang.org/stable/std/task/index.html#traits) ----------------------------------------------------------------------- [Wake](https://doc.rust-lang.org/stable/std/task/trait.Wake.html "trait std::task::Wake") The implementation of waking a task on an executor. [LocalWake](https://doc.rust-lang.org/stable/std/task/trait.LocalWake.html "trait std::task::LocalWake") Experimental An analogous trait to `Wake` but used to construct a `LocalWaker`. --- # std::panic - Rust [Module panic](https://doc.rust-lang.org/stable/std/panic/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module panic Copy item path =========================== 1.9.0 · [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#1-534) Expand description Panic support in the standard library. Structs[§](https://doc.rust-lang.org/stable/std/panic/index.html#structs) -------------------------------------------------------------------------- [AssertUnwindSafe](https://doc.rust-lang.org/stable/std/panic/struct.AssertUnwindSafe.html "struct std::panic::AssertUnwindSafe") A simple wrapper around a type to assert that it is unwind safe. [Location](https://doc.rust-lang.org/stable/std/panic/struct.Location.html "struct std::panic::Location") A struct containing information about the location of a panic. [PanicHookInfo](https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html "struct std::panic::PanicHookInfo") A struct providing information about a panic. Enums[§](https://doc.rust-lang.org/stable/std/panic/index.html#enums) ---------------------------------------------------------------------- [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") Experimental The configuration for whether and how the default panic hook will capture and display the backtrace. Traits[§](https://doc.rust-lang.org/stable/std/panic/index.html#traits) ------------------------------------------------------------------------ [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") A marker trait representing types where a shared reference is considered unwind safe. [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") A marker trait which represents “panic safe” types in Rust. Functions[§](https://doc.rust-lang.org/stable/std/panic/index.html#functions) ------------------------------------------------------------------------------ [catch\_unwind](https://doc.rust-lang.org/stable/std/panic/fn.catch_unwind.html "fn std::panic::catch_unwind") Invokes a closure, capturing the cause of an unwinding panic if one occurs. [panic\_any](https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html "fn std::panic::panic_any") Panics the current thread with the given message as the panic payload. [resume\_unwind](https://doc.rust-lang.org/stable/std/panic/fn.resume_unwind.html "fn std::panic::resume_unwind") Triggers a panic without invoking the panic hook. [set\_hook](https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html "fn std::panic::set_hook") Registers a custom panic hook, replacing the previously registered hook. [take\_hook](https://doc.rust-lang.org/stable/std/panic/fn.take_hook.html "fn std::panic::take_hook") Unregisters the current panic hook and returns it, registering the default hook in its place. [abort\_unwind](https://doc.rust-lang.org/stable/std/panic/fn.abort_unwind.html "fn std::panic::abort_unwind") Experimental Invokes a closure, aborting if the closure unwinds. [always\_abort](https://doc.rust-lang.org/stable/std/panic/fn.always_abort.html "fn std::panic::always_abort") Experimental Makes all future panics abort directly without running the panic hook or unwinding. [get\_backtrace\_style](https://doc.rust-lang.org/stable/std/panic/fn.get_backtrace_style.html "fn std::panic::get_backtrace_style") Experimental Checks whether the standard library’s panic hook will capture and print a backtrace. [set\_backtrace\_style](https://doc.rust-lang.org/stable/std/panic/fn.set_backtrace_style.html "fn std::panic::set_backtrace_style") Experimental Configures whether the default panic hook will capture and display a backtrace. [update\_hook](https://doc.rust-lang.org/stable/std/panic/fn.update_hook.html "fn std::panic::update_hook") Experimental Atomic combination of [`take_hook`](https://doc.rust-lang.org/stable/std/panic/fn.take_hook.html) and [`set_hook`](https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html) . Use this to replace the panic handler with a new panic handler that does something and then executes the old handler. Type Aliases[§](https://doc.rust-lang.org/stable/std/panic/index.html#types) ----------------------------------------------------------------------------- [PanicInfo](https://doc.rust-lang.org/stable/std/panic/type.PanicInfo.html "type std::panic::PanicInfo") Deprecated A struct providing information about a panic. --- # std::primitive - Rust [Module primitive](https://doc.rust-lang.org/stable/std/primitive/index.html#) ------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module primitive Copy item path =============================== 1.43.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#357) Expand description This module reexports the primitive types to allow usage that is not possibly shadowed by other declared types. This is normally only useful in macro generated code. An example of this is when generating a new struct and an impl for it: [ⓘ](https://doc.rust-lang.org/stable/std/primitive/index.html# "This example deliberately fails to compile") pub struct bool; impl QueryId for bool { const SOME_PROPERTY: bool = true; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++pub+struct+bool;%0A++++%0A++++impl+QueryId+for+bool+%7B%0A++++++++const+SOME_PROPERTY:+bool+=+true;%0A++++%7D%0A++++%0A++++trait+QueryId+%7B+const+SOME_PROPERTY:+::core::primitive::bool;+%7D%0A%7D&edition=2024 "Run code") Note that the `SOME_PROPERTY` associated constant would not compile, as its type `bool` refers to the struct, rather than to the primitive bool type. A correct implementation could look like: pub struct bool; impl QueryId for bool { const SOME_PROPERTY: ::core::primitive::bool = true; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(non_camel_case_types)%5D%0A++++pub+struct+bool;%0A++++%0A++++impl+QueryId+for+bool+%7B%0A++++++++const+SOME_PROPERTY:+::core::primitive::bool+=+true;%0A++++%7D%0A++++%0A++++trait+QueryId+%7B+const+SOME_PROPERTY:+::core::primitive::bool;+%7D%0A%7D&edition=2024 "Run code") We also used `::core` instead of `core`, because `core` can be shadowed, too. Paths, starting with `::`, are searched in the [extern prelude](https://doc.rust-lang.org/nightly/reference/names/preludes.html#extern-prelude) since Edition 2018. Re-exports[§](https://doc.rust-lang.org/stable/std/primitive/index.html#reexports) ----------------------------------------------------------------------------------- `pub use [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) ;` `pub use [char](https://doc.rust-lang.org/stable/std/primitive.char.html) ;` `pub use [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) ;` `pub use [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) ;` `pub use [i8](https://doc.rust-lang.org/stable/std/primitive.i8.html) ;` `pub use [i16](https://doc.rust-lang.org/stable/std/primitive.i16.html) ;` `pub use [i32](https://doc.rust-lang.org/stable/std/primitive.i32.html) ;` `pub use [i64](https://doc.rust-lang.org/stable/std/primitive.i64.html) ;` `pub use [i128](https://doc.rust-lang.org/stable/std/primitive.i128.html) ;` `pub use [isize](https://doc.rust-lang.org/stable/std/primitive.isize.html) ;` `pub use [str](https://doc.rust-lang.org/stable/std/primitive.str.html) ;` `pub use [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ;` `pub use [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) ;` `pub use [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ;` `pub use [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ;` `pub use [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) ;` `pub use [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ;` --- # std::fs - Rust [Module fs](https://doc.rust-lang.org/stable/std/fs/index.html#) ----------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module fs Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/fs.rs.html#1-3395) Expand description Filesystem manipulation operations. This module contains basic methods to manipulate the contents of the local filesystem. All methods in this module represent cross-platform filesystem operations. Extra platform-specific functionality can be found in the extension traits of `std::os::$platform`. [§](https://doc.rust-lang.org/stable/std/fs/index.html#time-of-check-to-time-of-use-toctou) Time of Check to Time of Use (TOCTOU) --------------------------------------------------------------------------------------------------------------------------------- Many filesystem operations are subject to a race condition known as “Time of Check to Time of Use” (TOCTOU). This occurs when a program checks a condition (like file existence or permissions) and then uses the result of that check to make a decision, but the condition may have changed between the check and the use. For example, checking if a file exists and then creating it if it doesn’t is vulnerable to TOCTOU - another process could create the file between your check and creation attempt. Another example is with symbolic links: when removing a directory, if another process replaces the directory with a symbolic link between the check and the removal operation, the removal might affect the wrong location. This is why operations like [`remove_dir_all`](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir_all.html "fn std::fs::remove_dir_all") need to use atomic operations to prevent such race conditions. To avoid TOCTOU issues: * Be aware that metadata operations (like [`metadata`](https://doc.rust-lang.org/stable/std/fs/fn.metadata.html "fn std::fs::metadata") or [`symlink_metadata`](https://doc.rust-lang.org/stable/std/fs/fn.symlink_metadata.html "fn std::fs::symlink_metadata") ) may be affected by changes made by other processes. * Use atomic operations when possible (like [`File::create_new`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.create_new "associated function std::fs::File::create_new") instead of checking existence then creating). * Keep file open for the duration of operations. Structs[§](https://doc.rust-lang.org/stable/std/fs/index.html#structs) ----------------------------------------------------------------------- [DirBuilder](https://doc.rust-lang.org/stable/std/fs/struct.DirBuilder.html "struct std::fs::DirBuilder") A builder used to create directories in various manners. [DirEntry](https://doc.rust-lang.org/stable/std/fs/struct.DirEntry.html "struct std::fs::DirEntry") Entries returned by the [`ReadDir`](https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html "struct std::fs::ReadDir") iterator. [File](https://doc.rust-lang.org/stable/std/fs/struct.File.html "struct std::fs::File") An object providing access to an open file on the filesystem. [FileTimes](https://doc.rust-lang.org/stable/std/fs/struct.FileTimes.html "struct std::fs::FileTimes") Representation of the various timestamps on a file. [FileType](https://doc.rust-lang.org/stable/std/fs/struct.FileType.html "struct std::fs::FileType") A structure representing a type of file with accessors for each file type. It is returned by [`Metadata::file_type`](https://doc.rust-lang.org/stable/std/fs/struct.Metadata.html#method.file_type "method std::fs::Metadata::file_type") method. [Metadata](https://doc.rust-lang.org/stable/std/fs/struct.Metadata.html "struct std::fs::Metadata") Metadata information about a file. [OpenOptions](https://doc.rust-lang.org/stable/std/fs/struct.OpenOptions.html "struct std::fs::OpenOptions") Options and flags which can be used to configure how a file is opened. [Permissions](https://doc.rust-lang.org/stable/std/fs/struct.Permissions.html "struct std::fs::Permissions") Representation of the various permissions on a file. [ReadDir](https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html "struct std::fs::ReadDir") Iterator over the entries in a directory. Enums[§](https://doc.rust-lang.org/stable/std/fs/index.html#enums) ------------------------------------------------------------------- [TryLockError](https://doc.rust-lang.org/stable/std/fs/enum.TryLockError.html "enum std::fs::TryLockError") An enumeration of possible errors which can occur while trying to acquire a lock from the [`try_lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock "method std::fs::File::try_lock") method and [`try_lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock_shared "method std::fs::File::try_lock_shared") method on a [`File`](https://doc.rust-lang.org/stable/std/fs/struct.File.html "struct std::fs::File") . Functions[§](https://doc.rust-lang.org/stable/std/fs/index.html#functions) --------------------------------------------------------------------------- [canonicalize](https://doc.rust-lang.org/stable/std/fs/fn.canonicalize.html "fn std::fs::canonicalize") Returns the canonical, absolute form of a path with all intermediate components normalized and symbolic links resolved. [copy](https://doc.rust-lang.org/stable/std/fs/fn.copy.html "fn std::fs::copy") Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. [create\_dir](https://doc.rust-lang.org/stable/std/fs/fn.create_dir.html "fn std::fs::create_dir") Creates a new, empty directory at the provided path [create\_dir\_all](https://doc.rust-lang.org/stable/std/fs/fn.create_dir_all.html "fn std::fs::create_dir_all") Recursively create a directory and all of its parent components if they are missing. [exists](https://doc.rust-lang.org/stable/std/fs/fn.exists.html "fn std::fs::exists") Returns `Ok(true)` if the path points at an existing entity. [hard\_link](https://doc.rust-lang.org/stable/std/fs/fn.hard_link.html "fn std::fs::hard_link") Creates a new hard link on the filesystem. [metadata](https://doc.rust-lang.org/stable/std/fs/fn.metadata.html "fn std::fs::metadata") Given a path, queries the file system to get information about a file, directory, etc. [read](https://doc.rust-lang.org/stable/std/fs/fn.read.html "fn std::fs::read") Reads the entire contents of a file into a bytes vector. [read\_dir](https://doc.rust-lang.org/stable/std/fs/fn.read_dir.html "fn std::fs::read_dir") Returns an iterator over the entries within a directory. [read\_link](https://doc.rust-lang.org/stable/std/fs/fn.read_link.html "fn std::fs::read_link") Reads a symbolic link, returning the file that the link points to. [read\_to\_string](https://doc.rust-lang.org/stable/std/fs/fn.read_to_string.html "fn std::fs::read_to_string") Reads the entire contents of a file into a string. [remove\_dir](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir.html "fn std::fs::remove_dir") Removes an empty directory. [remove\_dir\_all](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir_all.html "fn std::fs::remove_dir_all") Removes a directory at this path, after removing all its contents. Use carefully! [remove\_file](https://doc.rust-lang.org/stable/std/fs/fn.remove_file.html "fn std::fs::remove_file") Removes a file from the filesystem. [rename](https://doc.rust-lang.org/stable/std/fs/fn.rename.html "fn std::fs::rename") Renames a file or directory to a new name, replacing the original file if `to` already exists. [set\_permissions](https://doc.rust-lang.org/stable/std/fs/fn.set_permissions.html "fn std::fs::set_permissions") Changes the permissions found on a file or a directory. [soft\_link](https://doc.rust-lang.org/stable/std/fs/fn.soft_link.html "fn std::fs::soft_link") Deprecated Creates a new symbolic link on the filesystem. [symlink\_metadata](https://doc.rust-lang.org/stable/std/fs/fn.symlink_metadata.html "fn std::fs::symlink_metadata") Queries the metadata about a file without following symlinks. [write](https://doc.rust-lang.org/stable/std/fs/fn.write.html "fn std::fs::write") Writes a slice as the entire contents of a file. [set\_permissions\_nofollow](https://doc.rust-lang.org/stable/std/fs/fn.set_permissions_nofollow.html "fn std::fs::set_permissions_nofollow") Experimental Set the permissions of a file, unless it is a symlink. [set\_times](https://doc.rust-lang.org/stable/std/fs/fn.set_times.html "fn std::fs::set_times") Experimental Changes the timestamps of the file or directory at the specified path. [set\_times\_nofollow](https://doc.rust-lang.org/stable/std/fs/fn.set_times_nofollow.html "fn std::fs::set_times_nofollow") Experimental Changes the timestamps of the file or symlink at the specified path. --- # std::cell - Rust [Module cell](https://doc.rust-lang.org/stable/std/cell/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module cell Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#309) Expand description Shareable mutable containers. Rust memory safety is based on this rule: Given an object `T`, it is only possible to have one of the following: * Several immutable references (`&T`) to the object (also known as **aliasing**). * One mutable reference (`&mut T`) to the object (also known as **mutability**). This is enforced by the Rust compiler. However, there are situations where this rule is not flexible enough. Sometimes it is required to have multiple references to an object and yet mutate it. Shareable mutable containers exist to permit mutability in a controlled manner, even in the presence of aliasing. [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") , [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") , and [`OnceCell`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html "struct std::cell::OnceCell") allow doing this in a single-threaded way—they do not implement [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html) . (If you need to do aliasing and mutation among multiple threads, [`Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html) , [`RwLock`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html) , [`OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html) or [`atomic`](https://doc.rust-lang.org/stable/std/sync/atomic/index.html "mod std::sync::atomic") types are the correct data structures to do so). Values of the `Cell`, `RefCell`, and `OnceCell` types may be mutated through shared references (i.e. the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`) references. We say these cell types provide ‘interior mutability’ (mutable via `&T`), in contrast with typical Rust types that exhibit ‘inherited mutability’ (mutable only via `&mut T`). Cell types come in four flavors: `Cell`, `RefCell`, `OnceCell`, and `LazyCell`. Each provides a different way of providing safe interior mutability. ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#cellt) `Cell` [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") implements interior mutability by moving values in and out of the cell. That is, an `&mut T` to the inner value can never be obtained, and the value itself cannot be directly obtained without replacing it with something else. Both of these rules ensure that there is never more than one reference pointing to the inner value. This type provides the following methods: * For types that implement [`Copy`](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , the [`get`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get "method std::cell::Cell::get") method retrieves the current interior value by duplicating it. * For types that implement [`Default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") , the [`take`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.take "method std::cell::Cell::take") method replaces the current interior value with [`Default::default()`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default "associated function std::default::Default::default") and returns the replaced value. * All types have: * [`replace`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.replace "method std::cell::Cell::replace") : replaces the current interior value and returns the replaced value. * [`into_inner`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.into_inner "method std::cell::Cell::into_inner") : this method consumes the `Cell` and returns the interior value. * [`set`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.set "method std::cell::Cell::set") : this method replaces the interior value, dropping the replaced value. `Cell` is typically used for more simple types where copying or moving values isn’t too resource intensive (e.g. numbers), and should usually be preferred over other cell types when possible. For larger and non-copy types, `RefCell` provides some advantages. ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#refcellt) `RefCell` [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") uses Rust’s lifetimes to implement “dynamic borrowing”, a process whereby one can claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell`s are tracked at _runtime_, unlike Rust’s native reference types which are entirely tracked statically, at compile time. An immutable reference to a `RefCell`’s inner value (`&T`) can be obtained with [`borrow`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.borrow "method std::cell::RefCell::borrow") , and a mutable borrow (`&mut T`) can be obtained with [`borrow_mut`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.borrow_mut "method std::cell::RefCell::borrow_mut") . When these functions are called, they first verify that Rust’s borrow rules will be satisfied: any number of immutable borrows are allowed or a single mutable borrow is allowed, but never both. If a borrow is attempted that would violate these rules, the thread will panic. The corresponding [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html) version of `RefCell` is [`RwLock`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html) . ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#oncecellt) `OnceCell` [`OnceCell`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html "struct std::cell::OnceCell") is somewhat of a hybrid of `Cell` and `RefCell` that works for values that typically only need to be set once. This means that a reference `&T` can be obtained without moving or copying the inner value (unlike `Cell`) but also without runtime checks (unlike `RefCell`). However, its value can also not be updated once set unless you have a mutable reference to the `OnceCell`. `OnceCell` provides the following methods: * [`get`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html#method.get "method std::cell::OnceCell::get") : obtain a reference to the inner value * [`set`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html#method.set "method std::cell::OnceCell::set") : set the inner value if it is unset (returns a `Result`) * [`get_or_init`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html#method.get_or_init "method std::cell::OnceCell::get_or_init") : return the inner value, initializing it if needed * [`get_mut`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html#method.get_mut "method std::cell::OnceCell::get_mut") : provide a mutable reference to the inner value, only available if you have a mutable reference to the cell itself. The corresponding [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html) version of `OnceCell` is [`OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html) . ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#lazycellt-f) `LazyCell` A common pattern with OnceCell is, for a given OnceCell, to use the same function on every call to [`OnceCell::get_or_init`](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html#method.get_or_init "method std::cell::OnceCell::get_or_init") with that cell. This is what is offered by [`LazyCell`](https://doc.rust-lang.org/stable/std/cell/struct.LazyCell.html "struct std::cell::LazyCell") , which pairs cells of `T` with functions of `F`, and always calls `F` before it yields `&T`. This happens implicitly by simply attempting to dereference the LazyCell to get its contents, so its use is much more transparent with a place which has been initialized by a constant. More complicated patterns that don’t fit this description can be built on `OnceCell` instead. `LazyCell` works by providing an implementation of `impl Deref` that calls the function, so you can just use it by dereference (e.g. `*lazy_cell` or `lazy_cell.deref()`). The corresponding [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html) version of `LazyCell` is [`LazyLock`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html) . [§](https://doc.rust-lang.org/stable/std/cell/index.html#when-to-choose-interior-mutability) When to choose interior mutability ------------------------------------------------------------------------------------------------------------------------------- The more common inherited mutability, where one must have unique access to mutate a value, is one of the key language elements that enables Rust to reason strongly about pointer aliasing, statically preventing crash bugs. Because of that, inherited mutability is preferred, and interior mutability is something of a last resort. Since cell types enable mutation where it would otherwise be disallowed though, there are occasions when interior mutability might be appropriate, or even _must_ be used, e.g. * Introducing mutability ‘inside’ of something immutable * Implementation details of logically-immutable methods. * Mutating implementations of [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") . ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#introducing-mutability-inside-of-something-immutable) Introducing mutability ‘inside’ of something immutable Many shared smart pointer types, including [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html) and [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html) , provide containers that can be cloned and shared between multiple parties. Because the contained values may be multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be impossible to mutate data inside of these smart pointers at all. It’s very common then to put a `RefCell` inside shared pointer types to reintroduce mutability: use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::rc::Rc; fn main() { let shared_map: Rc> = Rc::new(RefCell::new(HashMap::new())); // Create a new block to limit the scope of the dynamic borrow { let mut map: RefMut<'_, _> = shared_map.borrow_mut(); map.insert("africa", 92388); map.insert("kyoto", 11837); map.insert("piccadilly", 11826); map.insert("marbles", 38); } // Note that if we had not let the previous borrow of the cache fall out // of scope then the subsequent borrow would cause a dynamic thread panic. // This is the major hazard of using `RefCell`. let total: i32 = shared_map.borrow().values().sum(); println!("{total}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::cell::%7BRefCell,+RefMut%7D;%0Ause+std::collections::HashMap;%0Ause+std::rc::Rc;%0A%0Afn+main()+%7B%0A++++let+shared_map:+Rc%3CRefCell%3C_%3E%3E+=+Rc::new(RefCell::new(HashMap::new()));%0A++++//+Create+a+new+block+to+limit+the+scope+of+the+dynamic+borrow%0A++++%7B%0A++++++++let+mut+map:+RefMut%3C%27_,+_%3E+=+shared_map.borrow_mut();%0A++++++++map.insert(%22africa%22,+92388);%0A++++++++map.insert(%22kyoto%22,+11837);%0A++++++++map.insert(%22piccadilly%22,+11826);%0A++++++++map.insert(%22marbles%22,+38);%0A++++%7D%0A%0A++++//+Note+that+if+we+had+not+let+the+previous+borrow+of+the+cache+fall+out%0A++++//+of+scope+then+the+subsequent+borrow+would+cause+a+dynamic+thread+panic.%0A++++//+This+is+the+major+hazard+of+using+%60RefCell%60.%0A++++let+total:+i32+=+shared_map.borrow().values().sum();%0A++++println!(%22%7Btotal%7D%22);%0A%7D&edition=2024 "Run code") Note that this example uses `Rc` and not `Arc`. `RefCell`s are for single-threaded scenarios. Consider using [`RwLock`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html) or [`Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html) if you need shared mutability in a multi-threaded situation. ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#implementation-details-of-logically-immutable-methods) Implementation details of logically-immutable methods Occasionally it may be desirable not to expose in an API that there is mutation happening “under the hood”. This may be because logically the operation is immutable, but e.g., caching forces the implementation to perform mutation; or because you must employ mutation to implement a trait method that was originally defined to take `&self`. use std::cell::OnceCell; struct Graph { edges: Vec<(i32, i32)>, span_tree_cache: OnceCell> } impl Graph { fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> { self.span_tree_cache .get_or_init(|| self.calc_span_tree()) .clone() } fn calc_span_tree(&self) -> Vec<(i32, i32)> { // Expensive computation goes here vec![] } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++use+std::cell::OnceCell;%0A++++%0A++++struct+Graph+%7B%0A++++++++edges:+Vec%3C(i32,+i32)%3E,%0A++++++++span_tree_cache:+OnceCell%3CVec%3C(i32,+i32)%3E%3E%0A++++%7D%0A++++%0A++++impl+Graph+%7B%0A++++++++fn+minimum_spanning_tree(%26self)+-%3E+Vec%3C(i32,+i32)%3E+%7B%0A++++++++++++self.span_tree_cache%0A++++++++++++++++.get_or_init(%7C%7C+self.calc_span_tree())%0A++++++++++++++++.clone()%0A++++++++%7D%0A++++%0A++++++++fn+calc_span_tree(%26self)+-%3E+Vec%3C(i32,+i32)%3E+%7B%0A++++++++++++//+Expensive+computation+goes+here%0A++++++++++++vec!%5B%5D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/cell/index.html#mutating-implementations-of-clone) Mutating implementations of `Clone` This is simply a special - but common - case of the previous: hiding mutability for operations that appear to be immutable. The [`clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone "method std::clone::Clone::clone") method is expected to not change the source value, and is declared to take `&self`, not `&mut self`. Therefore, any mutation that happens in the `clone` method must use cell types. For example, [`Rc`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html) maintains its reference counts within a `Cell`. use std::cell::Cell; use std::ptr::NonNull; use std::process::abort; use std::marker::PhantomData; struct Rc { ptr: NonNull>, phantom: PhantomData>, } struct RcInner { strong: Cell, refcount: Cell, value: T, } impl Clone for Rc { fn clone(&self) -> Rc { self.inc_strong(); Rc { ptr: self.ptr, phantom: PhantomData, } } } trait RcInnerPtr { fn inner(&self) -> &RcInner; fn strong(&self) -> usize { self.inner().strong.get() } fn inc_strong(&self) { self.inner() .strong .set(self.strong() .checked_add(1) .unwrap_or_else(|| abort() )); } } impl RcInnerPtr for Rc { fn inner(&self) -> &RcInner { unsafe { self.ptr.as_ref() } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++use+std::ptr::NonNull;%0A++++use+std::process::abort;%0A++++use+std::marker::PhantomData;%0A++++%0A++++struct+Rc%3CT:+?Sized%3E+%7B%0A++++++++ptr:+NonNull%3CRcInner%3CT%3E%3E,%0A++++++++phantom:+PhantomData%3CRcInner%3CT%3E%3E,%0A++++%7D%0A++++%0A++++struct+RcInner%3CT:+?Sized%3E+%7B%0A++++++++strong:+Cell%3Cusize%3E,%0A++++++++refcount:+Cell%3Cusize%3E,%0A++++++++value:+T,%0A++++%7D%0A++++%0A++++impl%3CT:+?Sized%3E+Clone+for+Rc%3CT%3E+%7B%0A++++++++fn+clone(%26self)+-%3E+Rc%3CT%3E+%7B%0A++++++++++++self.inc_strong();%0A++++++++++++Rc+%7B%0A++++++++++++++++ptr:+self.ptr,%0A++++++++++++++++phantom:+PhantomData,%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++trait+RcInnerPtr%3CT:+?Sized%3E+%7B%0A++++%0A++++++++fn+inner(%26self)+-%3E+%26RcInner%3CT%3E;%0A++++%0A++++++++fn+strong(%26self)+-%3E+usize+%7B%0A++++++++++++self.inner().strong.get()%0A++++++++%7D%0A++++%0A++++++++fn+inc_strong(%26self)+%7B%0A++++++++++++self.inner()%0A++++++++++++++++.strong%0A++++++++++++++++.set(self.strong()%0A+++++++++++++++++++++++++.checked_add(1)%0A+++++++++++++++++++++++++.unwrap_or_else(%7C%7C+abort()+));%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl%3CT:+?Sized%3E+RcInnerPtr%3CT%3E+for+Rc%3CT%3E+%7B%0A+++++++fn+inner(%26self)+-%3E+%26RcInner%3CT%3E+%7B%0A+++++++++++unsafe+%7B%0A+++++++++++++++self.ptr.as_ref()%0A+++++++++++%7D%0A+++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/cell/index.html#structs) ------------------------------------------------------------------------- [BorrowError](https://doc.rust-lang.org/stable/std/cell/struct.BorrowError.html "struct std::cell::BorrowError") An error returned by [`RefCell::try_borrow`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.try_borrow "method std::cell::RefCell::try_borrow") . [BorrowMutError](https://doc.rust-lang.org/stable/std/cell/struct.BorrowMutError.html "struct std::cell::BorrowMutError") An error returned by [`RefCell::try_borrow_mut`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html#method.try_borrow_mut "method std::cell::RefCell::try_borrow_mut") . [Cell](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") A mutable memory location. [LazyCell](https://doc.rust-lang.org/stable/std/cell/struct.LazyCell.html "struct std::cell::LazyCell") A value which is initialized on the first access. [OnceCell](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html "struct std::cell::OnceCell") A cell which can nominally be written to only once. [Ref](https://doc.rust-lang.org/stable/std/cell/struct.Ref.html "struct std::cell::Ref") Wraps a borrowed reference to a value in a `RefCell` box. A wrapper type for an immutably borrowed value from a `RefCell`. [RefCell](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") A mutable memory location with dynamically checked borrow rules [RefMut](https://doc.rust-lang.org/stable/std/cell/struct.RefMut.html "struct std::cell::RefMut") A wrapper type for a mutably borrowed value from a `RefCell`. [UnsafeCell](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html "struct std::cell::UnsafeCell") The core primitive for interior mutability in Rust. [SyncUnsafeCell](https://doc.rust-lang.org/stable/std/cell/struct.SyncUnsafeCell.html "struct std::cell::SyncUnsafeCell") Experimental [`UnsafeCell`](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html "struct std::cell::UnsafeCell") , but [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") . Traits[§](https://doc.rust-lang.org/stable/std/cell/index.html#traits) ----------------------------------------------------------------------- [CloneFromCell](https://doc.rust-lang.org/stable/std/cell/trait.CloneFromCell.html "trait std::cell::CloneFromCell") Experimental Types for which cloning `Cell` is sound. --- # std::process - Rust [Module process](https://doc.rust-lang.org/stable/std/process/index.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module process Copy item path ============================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/process.rs.html#1-2597) Expand description A module for working with processes. This module is mostly concerned with spawning and interacting with child processes, but it also provides [`abort`](https://doc.rust-lang.org/stable/std/process/fn.abort.html "fn std::process::abort") and [`exit`](https://doc.rust-lang.org/stable/std/process/fn.exit.html "fn std::process::exit") for terminating the current process. [§](https://doc.rust-lang.org/stable/std/process/index.html#spawning-a-process) Spawning a process -------------------------------------------------------------------------------------------------- The [`Command`](https://doc.rust-lang.org/stable/std/process/struct.Command.html "struct std::process::Command") struct is used to configure and spawn processes: use std::process::Command; let output = Command::new("echo") .arg("Hello world") .output() .expect("Failed to execute command"); assert_eq!(b"Hello world\n", output.stdout.as_slice()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::process::Command;%0A++++%0A++++let+output+=+Command::new(%22echo%22)%0A++++++++.arg(%22Hello+world%22)%0A++++++++.output()%0A++++++++.expect(%22Failed+to+execute+command%22);%0A++++%0A++++assert_eq!(b%22Hello+world%5Cn%22,+output.stdout.as_slice());%0A%7D&edition=2024 "Run code") Several methods on [`Command`](https://doc.rust-lang.org/stable/std/process/struct.Command.html "struct std::process::Command") , such as [`spawn`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.spawn "method std::process::Command::spawn") or [`output`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.output "method std::process::Command::output") , can be used to spawn a process. In particular, [`output`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.output "method std::process::Command::output") spawns the child process and waits until the process terminates, while [`spawn`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.spawn "method std::process::Command::spawn") will return a [`Child`](https://doc.rust-lang.org/stable/std/process/struct.Child.html "struct std::process::Child") that represents the spawned child process. [§](https://doc.rust-lang.org/stable/std/process/index.html#handling-io) Handling I/O ------------------------------------------------------------------------------------- The [`stdout`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.stdout "method std::process::Command::stdout") , [`stdin`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.stdin "method std::process::Command::stdin") , and [`stderr`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.stderr "method std::process::Command::stderr") of a child process can be configured by passing an [`Stdio`](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html "struct std::process::Stdio") to the corresponding method on [`Command`](https://doc.rust-lang.org/stable/std/process/struct.Command.html "struct std::process::Command") . Once spawned, they can be accessed from the [`Child`](https://doc.rust-lang.org/stable/std/process/struct.Child.html "struct std::process::Child") . For example, piping output from one command into another command can be done like so: use std::process::{Command, Stdio}; // stdout must be configured with `Stdio::piped` in order to use // `echo_child.stdout` let echo_child = Command::new("echo") .arg("Oh no, a tpyo!") .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); // Note that `echo_child` is moved here, but we won't be needing // `echo_child` anymore let echo_out = echo_child.stdout.expect("Failed to open echo stdout"); let mut sed_child = Command::new("sed") .arg("s/tpyo/typo/") .stdin(Stdio::from(echo_out)) .stdout(Stdio::piped()) .spawn() .expect("Failed to start sed process"); let output = sed_child.wait_with_output().expect("Failed to wait on sed"); assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::process::%7BCommand,+Stdio%7D;%0A++++%0A++++//+stdout+must+be+configured+with+%60Stdio::piped%60+in+order+to+use%0A++++//+%60echo_child.stdout%60%0A++++let+echo_child+=+Command::new(%22echo%22)%0A++++++++.arg(%22Oh+no,+a+tpyo!%22)%0A++++++++.stdout(Stdio::piped())%0A++++++++.spawn()%0A++++++++.expect(%22Failed+to+start+echo+process%22);%0A++++%0A++++//+Note+that+%60echo_child%60+is+moved+here,+but+we+won%27t+be+needing%0A++++//+%60echo_child%60+anymore%0A++++let+echo_out+=+echo_child.stdout.expect(%22Failed+to+open+echo+stdout%22);%0A++++%0A++++let+mut+sed_child+=+Command::new(%22sed%22)%0A++++++++.arg(%22s/tpyo/typo/%22)%0A++++++++.stdin(Stdio::from(echo_out))%0A++++++++.stdout(Stdio::piped())%0A++++++++.spawn()%0A++++++++.expect(%22Failed+to+start+sed+process%22);%0A++++%0A++++let+output+=+sed_child.wait_with_output().expect(%22Failed+to+wait+on+sed%22);%0A++++assert_eq!(b%22Oh+no,+a+typo!%5Cn%22,+output.stdout.as_slice());%0A%7D&edition=2024 "Run code") Note that [`ChildStderr`](https://doc.rust-lang.org/stable/std/process/struct.ChildStderr.html "struct std::process::ChildStderr") and [`ChildStdout`](https://doc.rust-lang.org/stable/std/process/struct.ChildStdout.html "struct std::process::ChildStdout") implement [`Read`](https://doc.rust-lang.org/stable/std/io/trait.Read.html "trait std::io::Read") and [`ChildStdin`](https://doc.rust-lang.org/stable/std/process/struct.ChildStdin.html "struct std::process::ChildStdin") implements [`Write`](https://doc.rust-lang.org/stable/std/io/trait.Write.html "trait std::io::Write") : use std::process::{Command, Stdio}; use std::io::Write; let mut child = Command::new("/bin/cat") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("failed to execute child"); // If the child process fills its stdout buffer, it may end up // waiting until the parent reads the stdout, and not be able to // read stdin in the meantime, causing a deadlock. // Writing from another thread ensures that stdout is being read // at the same time, avoiding the problem. let mut stdin = child.stdin.take().expect("failed to get stdin"); std::thread::spawn(move || { stdin.write_all(b"test").expect("failed to write to stdin"); }); let output = child .wait_with_output() .expect("failed to wait on child"); assert_eq!(b"test", output.stdout.as_slice()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::process::%7BCommand,+Stdio%7D;%0A++++use+std::io::Write;%0A++++%0A++++let+mut+child+=+Command::new(%22/bin/cat%22)%0A++++++++.stdin(Stdio::piped())%0A++++++++.stdout(Stdio::piped())%0A++++++++.spawn()%0A++++++++.expect(%22failed+to+execute+child%22);%0A++++%0A++++//+If+the+child+process+fills+its+stdout+buffer,+it+may+end+up%0A++++//+waiting+until+the+parent+reads+the+stdout,+and+not+be+able+to%0A++++//+read+stdin+in+the+meantime,+causing+a+deadlock.%0A++++//+Writing+from+another+thread+ensures+that+stdout+is+being+read%0A++++//+at+the+same+time,+avoiding+the+problem.%0A++++let+mut+stdin+=+child.stdin.take().expect(%22failed+to+get+stdin%22);%0A++++std::thread::spawn(move+%7C%7C+%7B%0A++++++++stdin.write_all(b%22test%22).expect(%22failed+to+write+to+stdin%22);%0A++++%7D);%0A++++%0A++++let+output+=+child%0A++++++++.wait_with_output()%0A++++++++.expect(%22failed+to+wait+on+child%22);%0A++++%0A++++assert_eq!(b%22test%22,+output.stdout.as_slice());%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/process/index.html#windows-argument-splitting) Windows argument splitting ------------------------------------------------------------------------------------------------------------------ On Unix systems arguments are passed to a new process as an array of strings, but on Windows arguments are passed as a single commandline string and it is up to the child process to parse it into an array. Therefore the parent and child processes must agree on how the commandline string is encoded. Most programs use the standard C run-time `argv`, which in practice results in consistent argument handling. However, some programs have their own way of parsing the commandline string. In these cases using [`arg`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.arg "method std::process::Command::arg") or [`args`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.args "method std::process::Command::args") may result in the child process seeing a different array of arguments than the parent process intended. Two ways of mitigating this are: * Validate untrusted input so that only a safe subset is allowed. * Use [`raw_arg`](https://doc.rust-lang.org/stable/std/os/windows/process/trait.CommandExt.html#tymethod.raw_arg "method std::os::windows::process::CommandExt::raw_arg") to build a custom commandline. This bypasses the escaping rules used by [`arg`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.arg "method std::process::Command::arg") so should be used with due caution. `cmd.exe` and `.bat` files use non-standard argument parsing and are especially vulnerable to malicious input as they may be used to run arbitrary shell commands. Untrusted arguments should be restricted as much as possible. For examples on handling this see [`raw_arg`](https://doc.rust-lang.org/stable/std/os/windows/process/trait.CommandExt.html#tymethod.raw_arg "method std::os::windows::process::CommandExt::raw_arg") . #### [§](https://doc.rust-lang.org/stable/std/process/index.html#batch-file-special-handling) Batch file special handling On Windows, `Command` uses the Windows API function [`CreateProcessW`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) to spawn new processes. An undocumented feature of this function is that when given a `.bat` file as the application to run, it will automatically convert that into running `cmd.exe /c` with the batch file as the next argument. For historical reasons Rust currently preserves this behavior when using [`Command::new`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.new "associated function std::process::Command::new") , and escapes the arguments according to `cmd.exe` rules. Due to the complexity of `cmd.exe` argument handling, it might not be possible to safely escape some special characters, and using them will result in an error being returned at process spawn. The set of unescapeable special characters might change between releases. Also note that running batch scripts in this way may be removed in the future and so should not be relied upon. Structs[§](https://doc.rust-lang.org/stable/std/process/index.html#structs) ---------------------------------------------------------------------------- [Child](https://doc.rust-lang.org/stable/std/process/struct.Child.html "struct std::process::Child") Representation of a running or exited child process. [ChildStderr](https://doc.rust-lang.org/stable/std/process/struct.ChildStderr.html "struct std::process::ChildStderr") A handle to a child process’s stderr. [ChildStdin](https://doc.rust-lang.org/stable/std/process/struct.ChildStdin.html "struct std::process::ChildStdin") A handle to a child process’s standard input (stdin). [ChildStdout](https://doc.rust-lang.org/stable/std/process/struct.ChildStdout.html "struct std::process::ChildStdout") A handle to a child process’s standard output (stdout). [Command](https://doc.rust-lang.org/stable/std/process/struct.Command.html "struct std::process::Command") A process builder, providing fine-grained control over how a new process should be spawned. [CommandArgs](https://doc.rust-lang.org/stable/std/process/struct.CommandArgs.html "struct std::process::CommandArgs") An iterator over the command arguments. [CommandEnvs](https://doc.rust-lang.org/stable/std/process/struct.CommandEnvs.html "struct std::process::CommandEnvs") An iterator over the command environment variables. [ExitCode](https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html "struct std::process::ExitCode") This type represents the status code the current process can return to its parent under normal termination. [ExitStatus](https://doc.rust-lang.org/stable/std/process/struct.ExitStatus.html "struct std::process::ExitStatus") Describes the result of a process after it has terminated. [Output](https://doc.rust-lang.org/stable/std/process/struct.Output.html "struct std::process::Output") The output of a finished process. [Stdio](https://doc.rust-lang.org/stable/std/process/struct.Stdio.html "struct std::process::Stdio") Describes what to do with a standard I/O stream for a child process when passed to the [`stdin`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.stdin "method std::process::Command::stdin") , [`stdout`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.stdout "method std::process::Command::stdout") , and [`stderr`](https://doc.rust-lang.org/stable/std/process/struct.Command.html#method.stderr "method std::process::Command::stderr") methods of [`Command`](https://doc.rust-lang.org/stable/std/process/struct.Command.html "struct std::process::Command") . [ExitStatusError](https://doc.rust-lang.org/stable/std/process/struct.ExitStatusError.html "struct std::process::ExitStatusError") Experimental Describes the result of a process after it has failed Traits[§](https://doc.rust-lang.org/stable/std/process/index.html#traits) -------------------------------------------------------------------------- [Termination](https://doc.rust-lang.org/stable/std/process/trait.Termination.html "trait std::process::Termination") A trait for implementing arbitrary return types in the `main` function. Functions[§](https://doc.rust-lang.org/stable/std/process/index.html#functions) -------------------------------------------------------------------------------- [abort](https://doc.rust-lang.org/stable/std/process/fn.abort.html "fn std::process::abort") Terminates the process in an abnormal fashion. [exit](https://doc.rust-lang.org/stable/std/process/fn.exit.html "fn std::process::exit") Terminates the current process with the specified exit code. [id](https://doc.rust-lang.org/stable/std/process/fn.id.html "fn std::process::id") Returns the OS-assigned process identifier associated with this process. --- # std::range - Rust [Module range](https://doc.rust-lang.org/stable/std/range/index.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module range Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#326) 🔬This is a nightly-only experimental API. (`new_range_api` [#125687](https://github.com/rust-lang/rust/issues/125687) ) Expand description [§](https://doc.rust-lang.org/stable/std/range/index.html#experimental-replacement-range-types) Experimental replacement range types ------------------------------------------------------------------------------------------------------------------------------------ The types within this module are meant to replace the existing `Range`, `RangeInclusive`, and `RangeFrom` types in a future edition. #![feature(new_range_api)] use core::range::{Range, RangeFrom, RangeInclusive}; let arr = [0, 1, 2, 3, 4]; assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); assert_eq!(arr[ .. 3 ], [0, 1, 2 ]); assert_eq!(arr[ ..=3 ], [0, 1, 2, 3 ]); assert_eq!(arr[ RangeFrom::from(1.. )], [ 1, 2, 3, 4]); assert_eq!(arr[ Range::from(1..3 )], [ 1, 2 ]); assert_eq!(arr[RangeInclusive::from(1..=3)], [ 1, 2, 3 ]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(new_range_api)%5D%0A%0Afn+main()+%7B%0A++++use+core::range::%7BRange,+RangeFrom,+RangeInclusive%7D;%0A++++%0A++++let+arr+=+%5B0,+1,+2,+3,+4%5D;%0A++++assert_eq!(arr%5B++++++++++++++++++++++..+++%5D,+%5B0,+1,+2,+3,+4%5D);%0A++++assert_eq!(arr%5B++++++++++++++++++++++..+3+%5D,+%5B0,+1,+2++++++%5D);%0A++++assert_eq!(arr%5B++++++++++++++++++++++..=3+%5D,+%5B0,+1,+2,+3+++%5D);%0A++++assert_eq!(arr%5B+++++RangeFrom::from(1..++)%5D,+%5B+++1,+2,+3,+4%5D);%0A++++assert_eq!(arr%5B+++++++++Range::from(1..3+)%5D,+%5B+++1,+2++++++%5D);%0A++++assert_eq!(arr%5BRangeInclusive::from(1..=3)%5D,+%5B+++1,+2,+3+++%5D);%0A%7D&version=nightly&edition=2024 "Run code") Modules[§](https://doc.rust-lang.org/stable/std/range/index.html#modules) -------------------------------------------------------------------------- [legacy](https://doc.rust-lang.org/stable/std/range/legacy/index.html "mod std::range::legacy") Experimental Legacy range types Structs[§](https://doc.rust-lang.org/stable/std/range/index.html#structs) -------------------------------------------------------------------------- [IterRange](https://doc.rust-lang.org/stable/std/range/struct.IterRange.html "struct std::range::IterRange") Experimental By-value [`Range`](https://doc.rust-lang.org/stable/std/range/struct.Range.html "struct std::range::Range") iterator. [IterRangeFrom](https://doc.rust-lang.org/stable/std/range/struct.IterRangeFrom.html "struct std::range::IterRangeFrom") Experimental By-value [`RangeFrom`](https://doc.rust-lang.org/stable/std/range/struct.RangeFrom.html "struct std::range::RangeFrom") iterator. [IterRangeInclusive](https://doc.rust-lang.org/stable/std/range/struct.IterRangeInclusive.html "struct std::range::IterRangeInclusive") Experimental By-value [`RangeInclusive`](https://doc.rust-lang.org/stable/std/range/struct.RangeInclusive.html "struct std::range::RangeInclusive") iterator. [Range](https://doc.rust-lang.org/stable/std/range/struct.Range.html "struct std::range::Range") Experimental A (half-open) range bounded inclusively below and exclusively above (`start..end` in a future edition). [RangeFrom](https://doc.rust-lang.org/stable/std/range/struct.RangeFrom.html "struct std::range::RangeFrom") Experimental A range only bounded inclusively below (`start..`). [RangeFull](https://doc.rust-lang.org/stable/std/range/struct.RangeFull.html "struct std::range::RangeFull") Experimental An unbounded range (`..`). [RangeInclusive](https://doc.rust-lang.org/stable/std/range/struct.RangeInclusive.html "struct std::range::RangeInclusive") Experimental A range bounded inclusively below and above (`start..=last`). [RangeTo](https://doc.rust-lang.org/stable/std/range/struct.RangeTo.html "struct std::range::RangeTo") Experimental A range only bounded exclusively above (`..end`). [RangeToInclusive](https://doc.rust-lang.org/stable/std/range/struct.RangeToInclusive.html "struct std::range::RangeToInclusive") Experimental A range only bounded inclusively above (`..=last`). Enums[§](https://doc.rust-lang.org/stable/std/range/index.html#enums) ---------------------------------------------------------------------- [Bound](https://doc.rust-lang.org/stable/std/range/enum.Bound.html "enum std::range::Bound") Experimental An endpoint of a range of keys. Traits[§](https://doc.rust-lang.org/stable/std/range/index.html#traits) ------------------------------------------------------------------------ [IntoBounds](https://doc.rust-lang.org/stable/std/range/trait.IntoBounds.html "trait std::range::IntoBounds") Experimental Used to convert a range into start and end bounds, consuming the range by value. [OneSidedRange](https://doc.rust-lang.org/stable/std/range/trait.OneSidedRange.html "trait std::range::OneSidedRange") Experimental `OneSidedRange` is implemented for built-in range types that are unbounded on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`, but `..`, `d..e`, and `f..=g` do not. [RangeBounds](https://doc.rust-lang.org/stable/std/range/trait.RangeBounds.html "trait std::range::RangeBounds") Experimental `RangeBounds` is implemented by Rust’s built-in range types, produced by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`. [Step](https://doc.rust-lang.org/stable/std/range/trait.Step.html "trait std::range::Step") Experimental Objects that have a notion of _successor_ and _predecessor_ operations. --- # std::path - Rust [Module path](https://doc.rust-lang.org/stable/std/path/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module path Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#1-3979) Expand description Cross-platform path manipulation. This module provides two types, [`PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") and [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") (akin to [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") and [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") ), for working with paths abstractly. These types are thin wrappers around [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") and [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") respectively, meaning that they work directly on strings according to the local platform’s path syntax. Paths can be parsed into [`Component`](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") s by iterating over the structure returned by the [`components`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.components "method std::path::Path::components") method on [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") . [`Component`](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") s roughly correspond to the substrings between path separators (`/` or `\`). You can reconstruct an equivalent path from components with the [`push`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.push "method std::path::PathBuf::push") method on [`PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") ; note that the paths may differ syntactically by the normalization described in the documentation for the [`components`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.components "method std::path::Path::components") method. ### [§](https://doc.rust-lang.org/stable/std/path/index.html#case-sensitivity) Case sensitivity Unless otherwise indicated path methods that do not access the filesystem, such as [`Path::starts_with`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.starts_with "method std::path::Path::starts_with") and [`Path::ends_with`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.ends_with "method std::path::Path::ends_with") , are case sensitive no matter the platform or filesystem. An exception to this is made for Windows drive letters. ### [§](https://doc.rust-lang.org/stable/std/path/index.html#simple-usage) Simple usage Path manipulation includes both parsing components from slices and building new owned paths. To parse a path, you can create a [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") slice from a [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") slice and start asking questions: use std::path::Path; use std::ffi::OsStr; let path = Path::new("/tmp/foo/bar.txt"); let parent = path.parent(); assert_eq!(parent, Some(Path::new("/tmp/foo"))); let file_stem = path.file_stem(); assert_eq!(file_stem, Some(OsStr::new("bar"))); let extension = path.extension(); assert_eq!(extension, Some(OsStr::new("txt"))); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::path::Path;%0A++++use+std::ffi::OsStr;%0A++++%0A++++let+path+=+Path::new(%22/tmp/foo/bar.txt%22);%0A++++%0A++++let+parent+=+path.parent();%0A++++assert_eq!(parent,+Some(Path::new(%22/tmp/foo%22)));%0A++++%0A++++let+file_stem+=+path.file_stem();%0A++++assert_eq!(file_stem,+Some(OsStr::new(%22bar%22)));%0A++++%0A++++let+extension+=+path.extension();%0A++++assert_eq!(extension,+Some(OsStr::new(%22txt%22)));%0A%7D&edition=2024 "Run code") To build or modify paths, use [`PathBuf`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") : use std::path::PathBuf; // This way works... let mut path = PathBuf::from("c:\\"); path.push("windows"); path.push("system32"); path.set_extension("dll"); // ... but push is best used if you don't know everything up // front. If you do, this way is better: let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::path::PathBuf;%0A++++%0A++++//+This+way+works...%0A++++let+mut+path+=+PathBuf::from(%22c:%5C%5C%22);%0A++++%0A++++path.push(%22windows%22);%0A++++path.push(%22system32%22);%0A++++%0A++++path.set_extension(%22dll%22);%0A++++%0A++++//+...+but+push+is+best+used+if+you+don%27t+know+everything+up%0A++++//+front.+If+you+do,+this+way+is+better:%0A++++let+path:+PathBuf+=+%5B%22c:%5C%5C%22,+%22windows%22,+%22system32.dll%22%5D.iter().collect();%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/path/index.html#structs) ------------------------------------------------------------------------- [Ancestors](https://doc.rust-lang.org/stable/std/path/struct.Ancestors.html "struct std::path::Ancestors") An iterator over [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") and its ancestors. [Components](https://doc.rust-lang.org/stable/std/path/struct.Components.html "struct std::path::Components") An iterator over the [`Component`](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") s of a [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") . [Display](https://doc.rust-lang.org/stable/std/path/struct.Display.html "struct std::path::Display") Helper struct for safely printing paths with [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") and `{}`. [Iter](https://doc.rust-lang.org/stable/std/path/struct.Iter.html "struct std::path::Iter") An iterator over the [`Component`](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") s of a [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") , as [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") slices. [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") A slice of a path (akin to [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") ). [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") An owned, mutable path (akin to [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") ). [PrefixComponent](https://doc.rust-lang.org/stable/std/path/struct.PrefixComponent.html "struct std::path::PrefixComponent") A structure wrapping a Windows path prefix as well as its unparsed string representation. [StripPrefixError](https://doc.rust-lang.org/stable/std/path/struct.StripPrefixError.html "struct std::path::StripPrefixError") An error returned from [`Path::strip_prefix`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.strip_prefix "method std::path::Path::strip_prefix") if the prefix was not found. [NormalizeError](https://doc.rust-lang.org/stable/std/path/struct.NormalizeError.html "struct std::path::NormalizeError") Experimental An error returned from [`Path::normalize_lexically`](https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.normalize_lexically "method std::path::Path::normalize_lexically") if a `..` parent reference would escape the path. Enums[§](https://doc.rust-lang.org/stable/std/path/index.html#enums) --------------------------------------------------------------------- [Component](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") A single component of a path. [Prefix](https://doc.rust-lang.org/stable/std/path/enum.Prefix.html "enum std::path::Prefix") Windows path prefixes, e.g., `C:` or `\\server\share`. Constants[§](https://doc.rust-lang.org/stable/std/path/index.html#constants) ----------------------------------------------------------------------------- [MAIN\_SEPARATOR](https://doc.rust-lang.org/stable/std/path/constant.MAIN_SEPARATOR.html "constant std::path::MAIN_SEPARATOR") The primary separator of path components for the current platform. [MAIN\_SEPARATOR\_STR](https://doc.rust-lang.org/stable/std/path/constant.MAIN_SEPARATOR_STR.html "constant std::path::MAIN_SEPARATOR_STR") The primary separator of path components for the current platform. Functions[§](https://doc.rust-lang.org/stable/std/path/index.html#functions) ----------------------------------------------------------------------------- [absolute](https://doc.rust-lang.org/stable/std/path/fn.absolute.html "fn std::path::absolute") Makes the path absolute without accessing the filesystem. [is\_separator](https://doc.rust-lang.org/stable/std/path/fn.is_separator.html "fn std::path::is_separator") Determines whether the character is one of the permitted path separators for the current platform. --- # std::sync - Rust [Module sync](https://doc.rust-lang.org/stable/std/sync/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module sync Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mod.rs.html#1-305) Expand description Useful synchronization primitives. ### [§](https://doc.rust-lang.org/stable/std/sync/index.html#the-need-for-synchronization) The need for synchronization Conceptually, a Rust program is a series of operations which will be executed on a computer. The timeline of events happening in the program is consistent with the order of the operations in the code. Consider the following code, operating on some global static variables: // FIXME(static_mut_refs): Do not allow `static_mut_refs` lint #![allow(static_mut_refs)] static mut A: u32 = 0; static mut B: u32 = 0; static mut C: u32 = 0; fn main() { unsafe { A = 3; B = 4; A = A + B; C = B; println!("{A} {B} {C}"); C = A; } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A//+FIXME(static_mut_refs):+Do+not+allow+%60static_mut_refs%60+lint%0A%23!%5Ballow(static_mut_refs)%5D%0A%0A%0Astatic+mut+A:+u32+=+0;%0Astatic+mut+B:+u32+=+0;%0Astatic+mut+C:+u32+=+0;%0A%0Afn+main()+%7B%0A++++unsafe+%7B%0A++++++++A+=+3;%0A++++++++B+=+4;%0A++++++++A+=+A+%2B+B;%0A++++++++C+=+B;%0A++++++++println!(%22%7BA%7D+%7BB%7D+%7BC%7D%22);%0A++++++++C+=+A;%0A++++%7D%0A%7D&edition=2024 "Run code") It appears as if some variables stored in memory are changed, an addition is performed, result is stored in `A` and the variable `C` is modified twice. When only a single thread is involved, the results are as expected: the line `7 4 4` gets printed. As for what happens behind the scenes, when optimizations are enabled the final generated machine code might look very different from the code: * The first store to `C` might be moved before the store to `A` or `B`, _as if_ we had written `C = 4; A = 3; B = 4`. * Assignment of `A + B` to `A` might be removed, since the sum can be stored in a temporary location until it gets printed, with the global variable never getting updated. * The final result could be determined just by looking at the code at compile time, so [constant folding](https://en.wikipedia.org/wiki/Constant_folding) might turn the whole block into a simple `println!("7 4 4")`. The compiler is allowed to perform any combination of these optimizations, as long as the final optimized code, when executed, produces the same results as the one without optimizations. Due to the [concurrency](https://en.wikipedia.org/wiki/Concurrency_(computer_science)) involved in modern computers, assumptions about the program’s execution order are often wrong. Access to global variables can lead to nondeterministic results, **even if** compiler optimizations are disabled, and it is **still possible** to introduce synchronization bugs. Note that thanks to Rust’s safety guarantees, accessing global (static) variables requires `unsafe` code, assuming we don’t use any of the synchronization primitives in this module. ### [§](https://doc.rust-lang.org/stable/std/sync/index.html#out-of-order-execution) Out-of-order execution Instructions can execute in a different order from the one we define, due to various reasons: * The **compiler** reordering instructions: If the compiler can issue an instruction at an earlier point, it will try to do so. For example, it might hoist memory loads at the top of a code block, so that the CPU can start [prefetching](https://en.wikipedia.org/wiki/Cache_prefetching) the values from memory. In single-threaded scenarios, this can cause issues when writing signal handlers or certain kinds of low-level code. Use [compiler fences](https://doc.rust-lang.org/stable/std/sync/atomic/fn.compiler_fence.html "fn std::sync::atomic::compiler_fence") to prevent this reordering. * A **single processor** executing instructions [out-of-order](https://en.wikipedia.org/wiki/Out-of-order_execution) : Modern CPUs are capable of [superscalar](https://en.wikipedia.org/wiki/Superscalar_processor) execution, i.e., multiple instructions might be executing at the same time, even though the machine code describes a sequential process. This kind of reordering is handled transparently by the CPU. * A **multiprocessor** system executing multiple hardware threads at the same time: In multi-threaded scenarios, you can use two kinds of primitives to deal with synchronization: * [memory fences](https://doc.rust-lang.org/stable/std/sync/atomic/fn.fence.html "fn std::sync::atomic::fence") to ensure memory accesses are made visible to other CPUs in the right order. * [atomic operations](https://doc.rust-lang.org/stable/std/sync/atomic/index.html "mod std::sync::atomic") to ensure simultaneous access to the same memory location doesn’t lead to undefined behavior. ### [§](https://doc.rust-lang.org/stable/std/sync/index.html#higher-level-synchronization-objects) Higher-level synchronization objects Most of the low-level synchronization primitives are quite error-prone and inconvenient to use, which is why the standard library also exposes some higher-level synchronization objects. These abstractions can be built out of lower-level primitives. For efficiency, the sync objects in the standard library are usually implemented with help from the operating system’s kernel, which is able to reschedule the threads while they are blocked on acquiring a lock. The following is an overview of the available synchronization objects: * [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") : Atomically Reference-Counted pointer, which can be used in multithreaded environments to prolong the lifetime of some data until all the threads have finished using it. * [`Barrier`](https://doc.rust-lang.org/stable/std/sync/struct.Barrier.html "struct std::sync::Barrier") : Ensures multiple threads will wait for each other to reach a point in the program, before continuing execution all together. * [`Condvar`](https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html "struct std::sync::Condvar") : Condition Variable, providing the ability to block a thread while waiting for an event to occur. * [`mpsc`](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html "mod std::sync::mpsc") : Multi-producer, single-consumer queues, used for message-based communication. Can provide a lightweight inter-thread synchronisation mechanism, at the cost of some extra memory. * [`mpmc`](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html "mod std::sync::mpmc") : Multi-producer, multi-consumer queues, used for message-based communication. Can provide a lightweight inter-thread synchronisation mechanism, at the cost of some extra memory. * [`Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html "struct std::sync::Mutex") : Mutual Exclusion mechanism, which ensures that at most one thread at a time is able to access some data. * [`Once`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html "struct std::sync::Once") : Used for a thread-safe, one-time global initialization routine. Mostly useful for implementing other types like [`OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html "struct std::sync::OnceLock") . * [`OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html "struct std::sync::OnceLock") : Used for thread-safe, one-time initialization of a variable, with potentially different initializers based on the caller. * [`LazyLock`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") : Used for thread-safe, one-time initialization of a variable, using one nullary initializer function provided at creation. * [`RwLock`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html "struct std::sync::RwLock") : Provides a mutual exclusion mechanism which allows multiple readers at the same time, while allowing only one writer at a time. In some cases, this can be more efficient than a mutex. Modules[§](https://doc.rust-lang.org/stable/std/sync/index.html#modules) ------------------------------------------------------------------------- [atomic](https://doc.rust-lang.org/stable/std/sync/atomic/index.html "mod std::sync::atomic") Atomic types [mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html "mod std::sync::mpsc") Multi-producer, single-consumer FIFO queue communication primitives. [mpmc](https://doc.rust-lang.org/stable/std/sync/mpmc/index.html "mod std::sync::mpmc") Experimental Multi-producer, multi-consumer FIFO queue communication primitives. [nonpoison](https://doc.rust-lang.org/stable/std/sync/nonpoison/index.html "mod std::sync::nonpoison") Experimental Non-poisoning synchronous locks. [poison](https://doc.rust-lang.org/stable/std/sync/poison/index.html "mod std::sync::poison") Experimental Synchronization objects that employ poisoning. Structs[§](https://doc.rust-lang.org/stable/std/sync/index.html#structs) ------------------------------------------------------------------------- [Arc](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") A thread-safe reference-counting pointer. ‘Arc’ stands for ‘Atomically Reference Counted’. [Barrier](https://doc.rust-lang.org/stable/std/sync/struct.Barrier.html "struct std::sync::Barrier") A barrier enables multiple threads to synchronize the beginning of some computation. [BarrierWaitResult](https://doc.rust-lang.org/stable/std/sync/struct.BarrierWaitResult.html "struct std::sync::BarrierWaitResult") A `BarrierWaitResult` is returned by [`Barrier::wait()`](https://doc.rust-lang.org/stable/std/sync/struct.Barrier.html#method.wait "method std::sync::Barrier::wait") when all threads in the [`Barrier`](https://doc.rust-lang.org/stable/std/sync/struct.Barrier.html "struct std::sync::Barrier") have rendezvoused. [Condvar](https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html "struct std::sync::Condvar") A Condition Variable [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") A value which is initialized on the first access. [Mutex](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html "struct std::sync::Mutex") A mutual exclusion primitive useful for protecting shared data [MutexGuard](https://doc.rust-lang.org/stable/std/sync/struct.MutexGuard.html "struct std::sync::MutexGuard") An RAII implementation of a “scoped lock” of a mutex. When this structure is dropped (falls out of scope), the lock will be unlocked. [Once](https://doc.rust-lang.org/stable/std/sync/struct.Once.html "struct std::sync::Once") A low-level synchronization primitive for one-time global execution. [OnceLock](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html "struct std::sync::OnceLock") A synchronization primitive which can nominally be written to only once. [OnceState](https://doc.rust-lang.org/stable/std/sync/struct.OnceState.html "struct std::sync::OnceState") State yielded to [`Once::call_once_force()`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html#method.call_once_force "method std::sync::Once::call_once_force") ’s closure parameter. The state can be used to query the poison status of the [`Once`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html "struct std::sync::Once") . [PoisonError](https://doc.rust-lang.org/stable/std/sync/struct.PoisonError.html "struct std::sync::PoisonError") A type of error which can be returned whenever a lock is acquired. [RwLock](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html "struct std::sync::RwLock") A reader-writer lock [RwLockReadGuard](https://doc.rust-lang.org/stable/std/sync/struct.RwLockReadGuard.html "struct std::sync::RwLockReadGuard") RAII structure used to release the shared read access of a lock when dropped. [RwLockWriteGuard](https://doc.rust-lang.org/stable/std/sync/struct.RwLockWriteGuard.html "struct std::sync::RwLockWriteGuard") RAII structure used to release the exclusive write access of a lock when dropped. [WaitTimeoutResult](https://doc.rust-lang.org/stable/std/sync/struct.WaitTimeoutResult.html "struct std::sync::WaitTimeoutResult") A type indicating whether a timed wait on a condition variable returned due to a time out or not. [Weak](https://doc.rust-lang.org/stable/std/sync/struct.Weak.html "struct std::sync::Weak") `Weak` is a version of [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") that holds a non-owning reference to the managed allocation. [Exclusive](https://doc.rust-lang.org/stable/std/sync/struct.Exclusive.html "struct std::sync::Exclusive") Experimental `Exclusive` provides _mutable_ access, also referred to as _exclusive_ access to the underlying value. However, it only permits _immutable_, or _shared_ access to the underlying value when that value is [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") . [MappedMutexGuard](https://doc.rust-lang.org/stable/std/sync/struct.MappedMutexGuard.html "struct std::sync::MappedMutexGuard") Experimental An RAII mutex guard returned by `MutexGuard::map`, which can point to a subfield of the protected data. When this structure is dropped (falls out of scope), the lock will be unlocked. [MappedRwLockReadGuard](https://doc.rust-lang.org/stable/std/sync/struct.MappedRwLockReadGuard.html "struct std::sync::MappedRwLockReadGuard") Experimental RAII structure used to release the shared read access of a lock when dropped, which can point to a subfield of the protected data. [MappedRwLockWriteGuard](https://doc.rust-lang.org/stable/std/sync/struct.MappedRwLockWriteGuard.html "struct std::sync::MappedRwLockWriteGuard") Experimental RAII structure used to release the exclusive write access of a lock when dropped, which can point to a subfield of the protected data. [ReentrantLock](https://doc.rust-lang.org/stable/std/sync/struct.ReentrantLock.html "struct std::sync::ReentrantLock") Experimental A re-entrant mutual exclusion lock [ReentrantLockGuard](https://doc.rust-lang.org/stable/std/sync/struct.ReentrantLockGuard.html "struct std::sync::ReentrantLockGuard") Experimental An RAII implementation of a “scoped lock” of a re-entrant lock. When this structure is dropped (falls out of scope), the lock will be unlocked. [UniqueArc](https://doc.rust-lang.org/stable/std/sync/struct.UniqueArc.html "struct std::sync::UniqueArc") Experimental A uniquely owned [`Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") . Enums[§](https://doc.rust-lang.org/stable/std/sync/index.html#enums) --------------------------------------------------------------------- [TryLockError](https://doc.rust-lang.org/stable/std/sync/enum.TryLockError.html "enum std::sync::TryLockError") An enumeration of possible errors associated with a [`TryLockResult`](https://doc.rust-lang.org/stable/std/sync/type.TryLockResult.html "type std::sync::TryLockResult") which can occur while trying to acquire a lock, from the [`try_lock`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html#method.try_lock "method std::sync::Mutex::try_lock") method on a [`Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html "struct std::sync::Mutex") or the [`try_read`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html#method.try_read "method std::sync::RwLock::try_read") and [`try_write`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html#method.try_write "method std::sync::RwLock::try_write") methods on an [`RwLock`](https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html "struct std::sync::RwLock") . Constants[§](https://doc.rust-lang.org/stable/std/sync/index.html#constants) ----------------------------------------------------------------------------- [ONCE\_INIT](https://doc.rust-lang.org/stable/std/sync/constant.ONCE_INIT.html "constant std::sync::ONCE_INIT") Deprecated Initialization value for static [`Once`](https://doc.rust-lang.org/stable/std/sync/struct.Once.html "struct std::sync::Once") values. Type Aliases[§](https://doc.rust-lang.org/stable/std/sync/index.html#types) ---------------------------------------------------------------------------- [LockResult](https://doc.rust-lang.org/stable/std/sync/type.LockResult.html "type std::sync::LockResult") A type alias for the result of a lock method which can be poisoned. [TryLockResult](https://doc.rust-lang.org/stable/std/sync/type.TryLockResult.html "type std::sync::TryLockResult") A type alias for the result of a nonblocking locking method. --- # std::arch - Rust [Module arch](https://doc.rust-lang.org/stable/std/arch/index.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module arch Copy item path ========================== 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/std/lib.rs.html#658) Expand description SIMD and vendor intrinsics module. This module is intended to be the gateway to architecture-specific intrinsic functions, typically related to SIMD (but not always!). Each architecture that Rust compiles to may contain a submodule here, which means that this is not a portable module! If you’re writing a portable library take care when using these APIs! Under this module you’ll find an architecture-named module, such as `x86_64`. Each `#[cfg(target_arch)]` that Rust can compile to may have a module entry here, only present on that particular target. For example the `i686-pc-windows-msvc` target will have an `x86` module here, whereas `x86_64-pc-windows-msvc` has `x86_64`. [§](https://doc.rust-lang.org/stable/std/arch/index.html#overview) Overview --------------------------------------------------------------------------- This module exposes vendor-specific intrinsics that typically correspond to a single machine instruction. These intrinsics are not portable: their availability is architecture-dependent, and not all machines of that architecture might provide the intrinsic. The `arch` module is intended to be a low-level implementation detail for higher-level APIs. Using it correctly can be quite tricky as you need to ensure at least a few guarantees are upheld: * The correct architecture’s module is used. For example the `arm` module isn’t available on the `x86_64-unknown-linux-gnu` target. This is typically done by ensuring that `#[cfg]` is used appropriately when using this module. * The CPU the program is currently running on supports the function being called. For example it is unsafe to call an AVX2 function on a CPU that doesn’t actually support AVX2. As a result of the latter of these guarantees all intrinsics in this module are `unsafe` and extra care needs to be taken when calling them! [§](https://doc.rust-lang.org/stable/std/arch/index.html#cpu-feature-detection) CPU Feature Detection ----------------------------------------------------------------------------------------------------- In order to call these APIs in a safe fashion there’s a number of mechanisms available to ensure that the correct CPU feature is available to call an intrinsic. Let’s consider, for example, the `_mm256_add_epi64` intrinsics on the `x86` and `x86_64` architectures. This function requires the AVX2 feature as [documented by Intel](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_add_epi64&expand=100) so to correctly call this function we need to (a) guarantee we only call it on `x86`/`x86_64` and (b) ensure that the CPU feature is available ### [§](https://doc.rust-lang.org/stable/std/arch/index.html#static-cpu-feature-detection) Static CPU Feature Detection The first option available to us is to conditionally compile code via the `#[cfg]` attribute. CPU features correspond to the `target_feature` cfg available, and can be used like so: [ⓘ](https://doc.rust-lang.org/stable/std/arch/index.html# "This example is not tested") #[cfg(\ all(\ any(target_arch = "x86", target_arch = "x86_64"),\ target_feature = "avx2"\ )\ )] fn foo() { #[cfg(target_arch = "x86")] use std::arch::x86::_mm256_add_epi64; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::_mm256_add_epi64; unsafe { _mm256_add_epi64(...); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bcfg(%0A++++++++all(%0A++++++++++++any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22),%0A++++++++++++target_feature+=+%22avx2%22%0A++++++++)%0A++++)%5D%0A++++fn+foo()+%7B%0A++++++++%23%5Bcfg(target_arch+=+%22x86%22)%5D%0A++++++++use+std::arch::x86::_mm256_add_epi64;%0A++++++++%23%5Bcfg(target_arch+=+%22x86_64%22)%5D%0A++++++++use+std::arch::x86_64::_mm256_add_epi64;%0A++++%0A++++++++unsafe+%7B%0A++++++++++++_mm256_add_epi64(...);%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Here we’re using `#[cfg(target_feature = "avx2")]` to conditionally compile this function into our module. This means that if the `avx2` feature is _enabled statically_ then we’ll use the `_mm256_add_epi64` function at runtime. The `unsafe` block here can be justified through the usage of `#[cfg]` to only compile the code in situations where the safety guarantees are upheld. Statically enabling a feature is typically done with the `-C target-feature` or `-C target-cpu` flags to the compiler. For example if your local CPU supports AVX2 then you can compile the above function with: $ RUSTFLAGS='-C target-cpu=native' cargo build Or otherwise you can specifically enable just the AVX2 feature: $ RUSTFLAGS='-C target-feature=+avx2' cargo build Note that when you compile a binary with a particular feature enabled it’s important to ensure that you only run the binary on systems which satisfy the required feature set. ### [§](https://doc.rust-lang.org/stable/std/arch/index.html#dynamic-cpu-feature-detection) Dynamic CPU Feature Detection Sometimes statically dispatching isn’t quite what you want. Instead you might want to build a portable binary that runs across a variety of CPUs, but at runtime it selects the most optimized implementation available. This allows you to build a “least common denominator” binary which has certain sections more optimized for different CPUs. Taking our previous example from before, we’re going to compile our binary _without_ AVX2 support, but we’d like to enable it for just one function. We can do that in a manner like: [ⓘ](https://doc.rust-lang.org/stable/std/arch/index.html# "This example is not tested") fn foo() { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { if is_x86_feature_detected!("avx2") { return unsafe { foo_avx2() }; } } // fallback implementation without using AVX2 } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[target_feature(enable = "avx2")] unsafe fn foo_avx2() { #[cfg(target_arch = "x86")] use std::arch::x86::_mm256_add_epi64; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::_mm256_add_epi64; unsafe { _mm256_add_epi64(...); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+foo()+%7B%0A++++++++%23%5Bcfg(any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22))%5D%0A++++++++%7B%0A++++++++++++if+is_x86_feature_detected!(%22avx2%22)+%7B%0A++++++++++++++++return+unsafe+%7B+foo_avx2()+%7D;%0A++++++++++++%7D%0A++++++++%7D%0A++++%0A++++++++//+fallback+implementation+without+using+AVX2%0A++++%7D%0A++++%0A++++%23%5Bcfg(any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22))%5D%0A++++%23%5Btarget_feature(enable+=+%22avx2%22)%5D%0A++++unsafe+fn+foo_avx2()+%7B%0A++++++++%23%5Bcfg(target_arch+=+%22x86%22)%5D%0A++++++++use+std::arch::x86::_mm256_add_epi64;%0A++++++++%23%5Bcfg(target_arch+=+%22x86_64%22)%5D%0A++++++++use+std::arch::x86_64::_mm256_add_epi64;%0A++++%0A++++++++unsafe+%7B+_mm256_add_epi64(...);+%7D%0A++++%7D%0A%7D&edition=2024 "Run code") There’s a couple of components in play here, so let’s go through them in detail! * First up we notice the `is_x86_feature_detected!` macro. Provided by the standard library, this macro will perform necessary runtime detection to determine whether the CPU the program is running on supports the specified feature. In this case the macro will expand to a boolean expression evaluating to whether the local CPU has the AVX2 feature or not. Note that this macro, like the `arch` module, is platform-specific. For example calling `is_x86_feature_detected!("avx2")` on ARM will be a compile time error. To ensure we don’t hit this error a statement level `#[cfg]` is used to only compile usage of the macro on `x86`/`x86_64`. * Next up we see our AVX2-enabled function, `foo_avx2`. This function is decorated with the `#[target_feature]` attribute which enables a CPU feature for just this one function. Using a compiler flag like `-C target-feature=+avx2` will enable AVX2 for the entire program, but using an attribute will only enable it for the one function. Usage of the `#[target_feature]` attribute currently requires the function to also be `unsafe`, as we see here. This is because the function can only be correctly called on systems which have the AVX2 (like the intrinsics themselves). And with all that we should have a working program! This program will run across all machines and it’ll use the optimized AVX2 implementation on machines where support is detected. [§](https://doc.rust-lang.org/stable/std/arch/index.html#ergonomics) Ergonomics ------------------------------------------------------------------------------- It’s important to note that using the `arch` module is not the easiest thing in the world, so if you’re curious to try it out you may want to brace yourself for some wordiness! The primary purpose of this module is to enable stable crates on crates.io to build up much more ergonomic abstractions which end up using SIMD under the hood. Over time these abstractions may also move into the standard library itself, but for now this module is tasked with providing the bare minimum necessary to use vendor intrinsics on stable Rust. [§](https://doc.rust-lang.org/stable/std/arch/index.html#other-architectures) Other architectures ------------------------------------------------------------------------------------------------- This documentation is only for one particular architecture, you can find others at: * [`x86`](https://doc.rust-lang.org/stable/core/arch/x86/index.html) * [`x86_64`](https://doc.rust-lang.org/stable/core/arch/x86_64/index.html) * [`arm`](https://doc.rust-lang.org/stable/core/arch/arm/index.html) * [`aarch64`](https://doc.rust-lang.org/stable/core/arch/aarch64/index.html) * [`riscv32`](https://doc.rust-lang.org/stable/core/arch/riscv32/index.html) * [`riscv64`](https://doc.rust-lang.org/stable/core/arch/riscv64/index.html) * [`mips`](https://doc.rust-lang.org/stable/core/arch/mips/index.html) * [`mips64`](https://doc.rust-lang.org/stable/core/arch/mips64/index.html) * [`powerpc`](https://doc.rust-lang.org/stable/core/arch/powerpc/index.html) * [`powerpc64`](https://doc.rust-lang.org/stable/core/arch/powerpc64/index.html) * [`nvptx`](https://doc.rust-lang.org/stable/core/arch/nvptx/index.html) * [`wasm32`](https://doc.rust-lang.org/stable/core/arch/wasm32/index.html) * [`loongarch32`](https://doc.rust-lang.org/stable/core/arch/loongarch32/index.html) * [`loongarch64`](https://doc.rust-lang.org/stable/core/arch/loongarch64/index.html) * [`s390x`](https://doc.rust-lang.org/stable/core/arch/s390x/index.html) [§](https://doc.rust-lang.org/stable/std/arch/index.html#examples) Examples --------------------------------------------------------------------------- First let’s take a look at not actually using any intrinsics but instead using LLVM’s auto-vectorization to produce optimized vectorized code for AVX2 and also for the default platform. fn main() { let mut dst = [0]; add_quickly(&[1], &[2], &mut dst); assert_eq!(dst[0], 3); } fn add_quickly(a: &[u8], b: &[u8], c: &mut [u8]) { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { // Note that this `unsafe` block is safe because we're testing // that the `avx2` feature is indeed available on our CPU. if is_x86_feature_detected!("avx2") { return unsafe { add_quickly_avx2(a, b, c) }; } } add_quickly_fallback(a, b, c) } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[target_feature(enable = "avx2")] unsafe fn add_quickly_avx2(a: &[u8], b: &[u8], c: &mut [u8]) { add_quickly_fallback(a, b, c) // the function below is inlined here } fn add_quickly_fallback(a: &[u8], b: &[u8], c: &mut [u8]) { for ((a, b), c) in a.iter().zip(b).zip(c) { *c = *a + *b; } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+dst+=+%5B0%5D;%0A++++add_quickly(%26%5B1%5D,+%26%5B2%5D,+%26mut+dst);%0A++++assert_eq!(dst%5B0%5D,+3);%0A%7D%0A%0Afn+add_quickly(a:+%26%5Bu8%5D,+b:+%26%5Bu8%5D,+c:+%26mut+%5Bu8%5D)+%7B%0A++++%23%5Bcfg(any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22))%5D%0A++++%7B%0A++++++++//+Note+that+this+%60unsafe%60+block+is+safe+because+we%27re+testing%0A++++++++//+that+the+%60avx2%60+feature+is+indeed+available+on+our+CPU.%0A++++++++if+is_x86_feature_detected!(%22avx2%22)+%7B%0A++++++++++++return+unsafe+%7B+add_quickly_avx2(a,+b,+c)+%7D;%0A++++++++%7D%0A++++%7D%0A%0A++++add_quickly_fallback(a,+b,+c)%0A%7D%0A%0A%23%5Bcfg(any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22))%5D%0A%23%5Btarget_feature(enable+=+%22avx2%22)%5D%0Aunsafe+fn+add_quickly_avx2(a:+%26%5Bu8%5D,+b:+%26%5Bu8%5D,+c:+%26mut+%5Bu8%5D)+%7B%0A++++add_quickly_fallback(a,+b,+c)+//+the+function+below+is+inlined+here%0A%7D%0A%0Afn+add_quickly_fallback(a:+%26%5Bu8%5D,+b:+%26%5Bu8%5D,+c:+%26mut+%5Bu8%5D)+%7B%0A++++for+((a,+b),+c)+in+a.iter().zip(b).zip(c)+%7B%0A++++++++*c+=+*a+%2B+*b;%0A++++%7D%0A%7D&edition=2024 "Run code") Next up let’s take a look at an example of manually using intrinsics. Here we’ll be using SSE4.1 features to implement hex encoding. fn main() { let mut dst = [0; 32]; hex_encode(b"\x01\x02\x03", &mut dst); assert_eq!(&dst[..6], b"010203"); let mut src = [0; 16]; for i in 0..16 { src[i] = (i + 1) as u8; } hex_encode(&src, &mut dst); assert_eq!(&dst, b"0102030405060708090a0b0c0d0e0f10"); } pub fn hex_encode(src: &[u8], dst: &mut [u8]) { let len = src.len().checked_mul(2).unwrap(); assert!(dst.len() >= len); #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { if is_x86_feature_detected!("sse4.1") { return unsafe { hex_encode_sse41(src, dst) }; } } hex_encode_fallback(src, dst) } // translated from // #[target_feature(enable = "sse4.1")] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] unsafe fn hex_encode_sse41(mut src: &[u8], dst: &mut [u8]) { #[cfg(target_arch = "x86")] use std::arch::x86::*; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; unsafe { let ascii_zero = _mm_set1_epi8(b'0' as i8); let nines = _mm_set1_epi8(9); let ascii_a = _mm_set1_epi8((b'a' - 9 - 1) as i8); let and4bits = _mm_set1_epi8(0xf); let mut i = 0_isize; while src.len() >= 16 { let invec = _mm_loadu_si128(src.as_ptr() as *const _); let masked1 = _mm_and_si128(invec, and4bits); let masked2 = _mm_and_si128(_mm_srli_epi64(invec, 4), and4bits); // return 0xff corresponding to the elements > 9, or 0x00 otherwise let cmpmask1 = _mm_cmpgt_epi8(masked1, nines); let cmpmask2 = _mm_cmpgt_epi8(masked2, nines); // add '0' or the offset depending on the masks let masked1 = _mm_add_epi8( masked1, _mm_blendv_epi8(ascii_zero, ascii_a, cmpmask1), ); let masked2 = _mm_add_epi8( masked2, _mm_blendv_epi8(ascii_zero, ascii_a, cmpmask2), ); // interleave masked1 and masked2 bytes let res1 = _mm_unpacklo_epi8(masked2, masked1); let res2 = _mm_unpackhi_epi8(masked2, masked1); _mm_storeu_si128(dst.as_mut_ptr().offset(i * 2) as *mut _, res1); _mm_storeu_si128( dst.as_mut_ptr().offset(i * 2 + 16) as *mut _, res2, ); src = &src[16..]; i += 16; } let i = i as usize; hex_encode_fallback(src, &mut dst[i * 2..]); } } fn hex_encode_fallback(src: &[u8], dst: &mut [u8]) { fn hex(byte: u8) -> u8 { static TABLE: &[u8] = b"0123456789abcdef"; TABLE[byte as usize] } for (byte, slots) in src.iter().zip(dst.chunks_mut(2)) { slots[0] = hex((*byte >> 4) & 0xf); slots[1] = hex(*byte & 0xf); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+dst+=+%5B0;+32%5D;%0A++++hex_encode(b%22%5Cx01%5Cx02%5Cx03%22,+%26mut+dst);%0A++++assert_eq!(%26dst%5B..6%5D,+b%22010203%22);%0A%0A++++let+mut+src+=+%5B0;+16%5D;%0A++++for+i+in+0..16+%7B%0A++++++++src%5Bi%5D+=+(i+%2B+1)+as+u8;%0A++++%7D%0A++++hex_encode(%26src,+%26mut+dst);%0A++++assert_eq!(%26dst,+b%220102030405060708090a0b0c0d0e0f10%22);%0A%7D%0A%0Apub+fn+hex_encode(src:+%26%5Bu8%5D,+dst:+%26mut+%5Bu8%5D)+%7B%0A++++let+len+=+src.len().checked_mul(2).unwrap();%0A++++assert!(dst.len()+%3E=+len);%0A%0A++++%23%5Bcfg(any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22))%5D%0A++++%7B%0A++++++++if+is_x86_feature_detected!(%22sse4.1%22)+%7B%0A++++++++++++return+unsafe+%7B+hex_encode_sse41(src,+dst)+%7D;%0A++++++++%7D%0A++++%7D%0A%0A++++hex_encode_fallback(src,+dst)%0A%7D%0A%0A//+translated+from%0A//+%3Chttps://github.com/Matherunner/bin2hex-sse/blob/master/base16_sse4.cpp%3E%0A%23%5Btarget_feature(enable+=+%22sse4.1%22)%5D%0A%23%5Bcfg(any(target_arch+=+%22x86%22,+target_arch+=+%22x86_64%22))%5D%0Aunsafe+fn+hex_encode_sse41(mut+src:+%26%5Bu8%5D,+dst:+%26mut+%5Bu8%5D)+%7B%0A++++%23%5Bcfg(target_arch+=+%22x86%22)%5D%0A++++use+std::arch::x86::*;%0A++++%23%5Bcfg(target_arch+=+%22x86_64%22)%5D%0A++++use+std::arch::x86_64::*;%0A%0A++++unsafe+%7B%0A++++++++let+ascii_zero+=+_mm_set1_epi8(b%270%27+as+i8);%0A++++++++let+nines+=+_mm_set1_epi8(9);%0A++++++++let+ascii_a+=+_mm_set1_epi8((b%27a%27+-+9+-+1)+as+i8);%0A++++++++let+and4bits+=+_mm_set1_epi8(0xf);%0A%0A++++++++let+mut+i+=+0_isize;%0A++++++++while+src.len()+%3E=+16+%7B%0A++++++++++++let+invec+=+_mm_loadu_si128(src.as_ptr()+as+*const+_);%0A%0A++++++++++++let+masked1+=+_mm_and_si128(invec,+and4bits);%0A++++++++++++let+masked2+=+_mm_and_si128(_mm_srli_epi64(invec,+4),+and4bits);%0A%0A++++++++++++//+return+0xff+corresponding+to+the+elements+%3E+9,+or+0x00+otherwise%0A++++++++++++let+cmpmask1+=+_mm_cmpgt_epi8(masked1,+nines);%0A++++++++++++let+cmpmask2+=+_mm_cmpgt_epi8(masked2,+nines);%0A%0A++++++++++++//+add+%270%27+or+the+offset+depending+on+the+masks%0A++++++++++++let+masked1+=+_mm_add_epi8(%0A++++++++++++++++masked1,%0A++++++++++++++++_mm_blendv_epi8(ascii_zero,+ascii_a,+cmpmask1),%0A++++++++++++);%0A++++++++++++let+masked2+=+_mm_add_epi8(%0A++++++++++++++++masked2,%0A++++++++++++++++_mm_blendv_epi8(ascii_zero,+ascii_a,+cmpmask2),%0A++++++++++++);%0A%0A++++++++++++//+interleave+masked1+and+masked2+bytes%0A++++++++++++let+res1+=+_mm_unpacklo_epi8(masked2,+masked1);%0A++++++++++++let+res2+=+_mm_unpackhi_epi8(masked2,+masked1);%0A%0A++++++++++++_mm_storeu_si128(dst.as_mut_ptr().offset(i+*+2)+as+*mut+_,+res1);%0A++++++++++++_mm_storeu_si128(%0A++++++++++++++++dst.as_mut_ptr().offset(i+*+2+%2B+16)+as+*mut+_,%0A++++++++++++++++res2,%0A++++++++++++);%0A++++++++++++src+=+%26src%5B16..%5D;%0A++++++++++++i+%2B=+16;%0A++++++++%7D%0A%0A++++++++let+i+=+i+as+usize;%0A++++++++hex_encode_fallback(src,+%26mut+dst%5Bi+*+2..%5D);%0A++++%7D%0A%7D%0A%0Afn+hex_encode_fallback(src:+%26%5Bu8%5D,+dst:+%26mut+%5Bu8%5D)+%7B%0A++++fn+hex(byte:+u8)+-%3E+u8+%7B%0A++++++++static+TABLE:+%26%5Bu8%5D+=+b%220123456789abcdef%22;%0A++++++++TABLE%5Bbyte+as+usize%5D%0A++++%7D%0A%0A++++for+(byte,+slots)+in+src.iter().zip(dst.chunks_mut(2))+%7B%0A++++++++slots%5B0%5D+=+hex((*byte+%3E%3E+4)+%26+0xf);%0A++++++++slots%5B1%5D+=+hex(*byte+%26+0xf);%0A++++%7D%0A%7D&edition=2024 "Run code") Re-exports[§](https://doc.rust-lang.org/stable/std/arch/index.html#reexports) ------------------------------------------------------------------------------ `pub use core::[arch](https://doc.rust-lang.org/stable/core/arch/index.html "mod core::arch") ::*;` Macros[§](https://doc.rust-lang.org/stable/std/arch/index.html#macros) ----------------------------------------------------------------------- [is\_aarch64\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_aarch64_feature_detected.html "macro std::arch::is_aarch64_feature_detected") This macro tests, at runtime, whether an `aarch64` feature is enabled on aarch64 platforms. Currently most features are only supported on linux-based platforms. [is\_loongarch\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_loongarch_feature_detected.html "macro std::arch::is_loongarch_feature_detected") Checks if `loongarch` feature is enabled. Supported arguments are: [is\_riscv\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_riscv_feature_detected.html "macro std::arch::is_riscv_feature_detected") A macro to test at _runtime_ whether instruction sets are available on RISC-V platforms. [is\_x86\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_x86_feature_detected.html "macro std::arch::is_x86_feature_detected") A macro to test at _runtime_ whether a CPU feature is available on x86/x86-64 platforms. [is\_arm\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_arm_feature_detected.html "macro std::arch::is_arm_feature_detected") Experimental Checks if `arm` feature is enabled. [is\_mips64\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_mips64_feature_detected.html "macro std::arch::is_mips64_feature_detected") Experimental Checks if `mips64` feature is enabled. [is\_mips\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_mips_feature_detected.html "macro std::arch::is_mips_feature_detected") Experimental Checks if `mips` feature is enabled. [is\_powerpc64\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_powerpc64_feature_detected.html "macro std::arch::is_powerpc64_feature_detected") Experimental Checks if `powerpc` feature is enabled. [is\_powerpc\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_powerpc_feature_detected.html "macro std::arch::is_powerpc_feature_detected") Experimental Checks if `powerpc` feature is enabled. [is\_s390x\_feature\_detected](https://doc.rust-lang.org/stable/std/arch/macro.is_s390x_feature_detected.html "macro std::arch::is_s390x_feature_detected") Experimental Checks if `s390x` feature is enabled. --- # include_str in std - Rust [include\_str](https://doc.rust-lang.org/stable/std/macro.include_str.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro include\_str Copy item path ================================= 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1320) macro_rules! include_str { ($file:expr $(,)?) => { ... }; } Expand description Includes a UTF-8 encoded file as a string. The file is located relative to the current file (similarly to how modules are found). The provided path is interpreted in a platform-specific way at compile time. So, for instance, an invocation with a Windows path containing backslashes `\` would not compile correctly on Unix. This macro will yield an expression of type `&'static str` which is the contents of the file. [§](https://doc.rust-lang.org/stable/std/macro.include_str.html#examples) Examples ---------------------------------------------------------------------------------- Assume there are two files in the same directory with the following contents: File ‘spanish.in’: adiós File ‘main.rs’: [ⓘ](https://doc.rust-lang.org/stable/std/macro.include_str.html# "This example is not tested") fn main() { let my_str = include_str!("spanish.in"); assert_eq!(my_str, "adiós\n"); print!("{my_str}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+my_str+=+include_str!(%22spanish.in%22);%0A++++assert_eq!(my_str,+%22adi%C3%B3s%5Cn%22);%0A++++print!(%22%7Bmy_str%7D%22);%0A%7D&edition=2024 "Run code") Compiling ‘main.rs’ and running the resulting binary will print “adiós”. --- # include_bytes in std - Rust [include\_bytes](https://doc.rust-lang.org/stable/std/macro.include_bytes.html#) --------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro include\_bytes Copy item path =================================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1360) macro_rules! include_bytes { ($file:expr $(,)?) => { ... }; } Expand description Includes a file as a reference to a byte array. The file is located relative to the current file (similarly to how modules are found). The provided path is interpreted in a platform-specific way at compile time. So, for instance, an invocation with a Windows path containing backslashes `\` would not compile correctly on Unix. This macro will yield an expression of type `&'static [u8; N]` which is the contents of the file. [§](https://doc.rust-lang.org/stable/std/macro.include_bytes.html#examples) Examples ------------------------------------------------------------------------------------ Assume there are two files in the same directory with the following contents: File ‘spanish.in’: adiós File ‘main.rs’: [ⓘ](https://doc.rust-lang.org/stable/std/macro.include_bytes.html# "This example is not tested") fn main() { let bytes = include_bytes!("spanish.in"); assert_eq!(bytes, b"adi\xc3\xb3s\n"); print!("{}", String::from_utf8_lossy(bytes)); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+bytes+=+include_bytes!(%22spanish.in%22);%0A++++assert_eq!(bytes,+b%22adi%5Cxc3%5Cxb3s%5Cn%22);%0A++++print!(%22%7B%7D%22,+String::from_utf8_lossy(bytes));%0A%7D&edition=2024 "Run code") Compiling ‘main.rs’ and running the resulting binary will print “adiós”. --- # is_x86_feature_detected in std - Rust [is\_x86\_feature\_detected](https://doc.rust-lang.org/stable/std/macro.is_x86_feature_detected.html#) ------------------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro is\_x86\_feature\_detected Copy item path =============================================== 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/std_detect/detect/arch/x86.rs.html#18-284) macro_rules! is_x86_feature_detected { ("aes") => { ... }; ("pclmulqdq") => { ... }; ("rdrand") => { ... }; ("rdseed") => { ... }; ("tsc") => { ... }; ("mmx") => { ... }; ("sse") => { ... }; ("sse2") => { ... }; ("sse3") => { ... }; ("ssse3") => { ... }; ("sse4.1") => { ... }; ("sse4.2") => { ... }; ("sse4a") => { ... }; ("sha") => { ... }; ("avx") => { ... }; ("avx2") => { ... }; ("sha512") => { ... }; ("sm3") => { ... }; ("sm4") => { ... }; ("avx512f") => { ... }; ("avx512cd") => { ... }; ("avx512er") => { ... }; ("avx512pf") => { ... }; ("avx512bw") => { ... }; ("avx512dq") => { ... }; ("avx512vl") => { ... }; ("avx512ifma") => { ... }; ("avx512vbmi") => { ... }; ("avx512vpopcntdq") => { ... }; ("avx512vbmi2") => { ... }; ("gfni") => { ... }; ("vaes") => { ... }; ("vpclmulqdq") => { ... }; ("avx512vnni") => { ... }; ("avx512bitalg") => { ... }; ("avx512bf16") => { ... }; ("avx512vp2intersect") => { ... }; ("avx512fp16") => { ... }; ("avxifma") => { ... }; ("avxneconvert") => { ... }; ("avxvnni") => { ... }; ("avxvnniint16") => { ... }; ("avxvnniint8") => { ... }; ("amx-tile") => { ... }; ("amx-int8") => { ... }; ("amx-bf16") => { ... }; ("amx-fp16") => { ... }; ("amx-complex") => { ... }; ("amx-avx512") => { ... }; ("amx-fp8") => { ... }; ("amx-movrs") => { ... }; ("amx-tf32") => { ... }; ("amx-transpose") => { ... }; ("apxf") => { ... }; ("avx10.1") => { ... }; ("avx10.2") => { ... }; ("f16c") => { ... }; ("fma") => { ... }; ("bmi1") => { ... }; ("bmi2") => { ... }; ("lzcnt") => { ... }; ("tbm") => { ... }; ("popcnt") => { ... }; ("fxsr") => { ... }; ("xsave") => { ... }; ("xsaveopt") => { ... }; ("xsaves") => { ... }; ("xsavec") => { ... }; ("cmpxchg16b") => { ... }; ("kl") => { ... }; ("widekl") => { ... }; ("adx") => { ... }; ("rtm") => { ... }; ("movbe") => { ... }; ("movrs") => { ... }; ("ermsb") => { ... }; ("xop") => { ... }; ("abm") => { ... }; ("avx512gfni") => { ... }; ("avx512vaes") => { ... }; ("avx512vpclmulqdq") => { ... }; ($t:tt,) => { ... }; ($t:tt) => { ... }; } Expand description A macro to test at _runtime_ whether a CPU feature is available on x86/x86-64 platforms. This macro is provided in the standard library and will detect at runtime whether the specified CPU feature is detected. This does **not** resolve at compile time unless the specified feature is already enabled for the entire crate. Runtime detection currently relies mostly on the `cpuid` instruction. This macro only takes one argument which is a string literal of the feature being tested for. The feature names supported are the lowercase versions of the ones defined by Intel in [their documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide) . ### [§](https://doc.rust-lang.org/stable/std/macro.is_x86_feature_detected.html#supported-arguments) Supported arguments This macro supports the same names that `#[target_feature]` supports. Unlike `#[target_feature]`, however, this macro does not support names separated with a comma. Instead testing for multiple features must be done through separate macro invocations for now. Supported arguments are: * `"aes"` * `"pclmulqdq"` * `"rdrand"` * `"rdseed"` * `"tsc"` * `"mmx"` * `"sse"` * `"sse2"` * `"sse3"` * `"ssse3"` * `"sse4.1"` * `"sse4.2"` * `"sse4a"` * `"sha"` * `"avx"` * `"avx2"` * `"sha512"` * `"sm3"` * `"sm4"` * `"avx512f"` * `"avx512cd"` * `"avx512er"` * `"avx512pf"` * `"avx512bw"` * `"avx512dq"` * `"avx512vl"` * `"avx512ifma"` * `"avx512vbmi"` * `"avx512vpopcntdq"` * `"avx512vbmi2"` * `"gfni"` * `"vaes"` * `"vpclmulqdq"` * `"avx512vnni"` * `"avx512bitalg"` * `"avx512bf16"` * `"avx512vp2intersect"` * `"avx512fp16"` * `"avxvnni"` * `"avxifma"` * `"avxneconvert"` * `"avxvnniint8"` * `"avxvnniint16"` * `"amx-tile"` * `"amx-int8"` * `"amx-bf16"` * `"amx-fp16"` * `"amx-complex"` * `"amx-avx512"` * `"amx-fp8"` * `"amx-movrs"` * `"amx-tf32"` * `"amx-transpose"` * `"f16c"` * `"fma"` * `"bmi1"` * `"bmi2"` * `"abm"` * `"lzcnt"` * `"tbm"` * `"popcnt"` * `"fxsr"` * `"xsave"` * `"xsaveopt"` * `"xsaves"` * `"xsavec"` * `"cmpxchg16b"` * `"kl"` * `"widekl"` * `"adx"` * `"rtm"` * `"movbe"` * `"ermsb"` * `"movrs"` * `"xop"` --- # std::marker - Rust [Module marker](https://doc.rust-lang.org/stable/std/marker/index.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module marker Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#296) Expand description Primitive traits and types representing basic properties of types. Rust types can be classified in various useful ways according to their intrinsic properties. These classifications are represented as traits. Structs[§](https://doc.rust-lang.org/stable/std/marker/index.html#structs) --------------------------------------------------------------------------- [PhantomData](https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html "struct std::marker::PhantomData") Zero-sized type used to mark things that “act like” they own a `T`. [PhantomPinned](https://doc.rust-lang.org/stable/std/marker/struct.PhantomPinned.html "struct std::marker::PhantomPinned") A marker type which does not implement `Unpin`. [PhantomContravariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariant.html "struct std::marker::PhantomContravariant") Experimental Zero-sized type used to mark a type parameter as contravariant. [PhantomContravariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariantLifetime.html "struct std::marker::PhantomContravariantLifetime") Experimental Zero-sized type used to mark a lifetime as contravariant. [PhantomCovariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariant.html "struct std::marker::PhantomCovariant") Experimental Zero-sized type used to mark a type parameter as covariant. [PhantomCovariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariantLifetime.html "struct std::marker::PhantomCovariantLifetime") Experimental Zero-sized type used to mark a lifetime as covariant. [PhantomInvariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariant.html "struct std::marker::PhantomInvariant") Experimental Zero-sized type used to mark a type parameter as invariant. [PhantomInvariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariantLifetime.html "struct std::marker::PhantomInvariantLifetime") Experimental Zero-sized type used to mark a lifetime as invariant. Traits[§](https://doc.rust-lang.org/stable/std/marker/index.html#traits) ------------------------------------------------------------------------- [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") Types whose values can be duplicated simply by copying bits. [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") Types that can be transferred across thread boundaries. [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") Types with a constant size known at compile time. [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") Types for which it is safe to share references between threads. [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") Types that do not require any pinning guarantees. [ConstParamTy\_](https://doc.rust-lang.org/stable/std/marker/trait.ConstParamTy_.html "trait std::marker::ConstParamTy_") Experimental A marker for types which can be used as types of `const` generic parameters. [Destruct](https://doc.rust-lang.org/stable/std/marker/trait.Destruct.html "trait std::marker::Destruct") Experimental A marker for types that can be dropped. [DiscriminantKind](https://doc.rust-lang.org/stable/std/marker/trait.DiscriminantKind.html "trait std::marker::DiscriminantKind") Experimental Compiler-internal trait used to indicate the type of enum discriminants. [FnPtr](https://doc.rust-lang.org/stable/std/marker/trait.FnPtr.html "trait std::marker::FnPtr") Experimental A common trait implemented by all function pointers. [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") Experimental Used to determine whether a type contains any `UnsafeCell` internally, but not through an indirection. This affects, for example, whether a `static` of that type is placed in read-only static memory or writable static memory. This can be used to declare that a constant with a generic type will not contain interior mutability, and subsequently allow placing the constant behind references. [MetaSized](https://doc.rust-lang.org/stable/std/marker/trait.MetaSized.html "trait std::marker::MetaSized") Experimental Types with a size that can be determined from pointer metadata. [PointeeSized](https://doc.rust-lang.org/stable/std/marker/trait.PointeeSized.html "trait std::marker::PointeeSized") Experimental Types that may or may not have a size. [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") Experimental Required trait for constants used in pattern matches. [Tuple](https://doc.rust-lang.org/stable/std/marker/trait.Tuple.html "trait std::marker::Tuple") Experimental A marker for tuple types. [Unsize](https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html "trait std::marker::Unsize") Experimental Types that can be “unsized” to a dynamically-sized type. [Variance](https://doc.rust-lang.org/stable/std/marker/trait.Variance.html "trait std::marker::Variance") Experimental A marker trait for phantom variance types. Functions[§](https://doc.rust-lang.org/stable/std/marker/index.html#functions) ------------------------------------------------------------------------------- [variance](https://doc.rust-lang.org/stable/std/marker/fn.variance.html "fn std::marker::variance") Experimental Construct a variance marker; equivalent to [`Default::default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default "associated function std::default::Default::default") . Derive Macros[§](https://doc.rust-lang.org/stable/std/marker/index.html#derives) --------------------------------------------------------------------------------- [Copy](https://doc.rust-lang.org/stable/std/marker/derive.Copy.html "derive std::marker::Copy") Derive macro generating an impl of the trait `Copy`. [CoercePointee](https://doc.rust-lang.org/stable/std/marker/derive.CoercePointee.html "derive std::marker::CoercePointee") Experimental Derive macro that makes a smart pointer usable with trait objects. [ConstParamTy](https://doc.rust-lang.org/stable/std/marker/derive.ConstParamTy.html "derive std::marker::ConstParamTy") Experimental Derive macro generating an impl of the trait `ConstParamTy`. --- # matches in std - Rust [matches](https://doc.rust-lang.org/stable/std/macro.matches.html#) -------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro matches Copy item path ============================ 1.42.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#434) macro_rules! matches { ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => { ... }; } Expand description 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!`](https://doc.rust-lang.org/stable/std/assert_matches/macro.assert_matches.html "macro std::assert_matches::assert_matches") as it will print the debug representation of the value if the assertion fails. [§](https://doc.rust-lang.org/stable/std/macro.matches.html#examples) Examples ------------------------------------------------------------------------------ let foo = 'f'; assert!(matches!(foo, 'A'..='Z' | 'a'..='z')); let bar = Some(4); assert!(matches!(bar, Some(x) if x > 2)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+foo+=+%27f%27;%0A++++assert!(matches!(foo,+%27A%27..=%27Z%27+%7C+%27a%27..=%27z%27));%0A++++%0A++++let+bar+=+Some(4);%0A++++assert!(matches!(bar,+Some(x)+if+x+%3E+2));%0A%7D&edition=2024 "Run code") --- # line in std - Rust [line](https://doc.rust-lang.org/stable/std/macro.line.html#) -------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro line Copy item path ========================= 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1177) macro_rules! line { () => { ... }; } Expand description Expands to the line number on which it was invoked. With [`column!`](https://doc.rust-lang.org/stable/std/macro.column.html "macro std::column") and [`file!`](https://doc.rust-lang.org/stable/std/macro.file.html "macro std::file") , these macros provide debugging information for developers about the location within the source. The expanded expression has type `u32` and is 1-based, so the first line in each file evaluates to 1, the second to 2, etc. This is consistent with error messages by common compilers or popular editors. The returned line is _not necessarily_ the line of the `line!` invocation itself, but rather the first macro invocation leading up to the invocation of the `line!` macro. [§](https://doc.rust-lang.org/stable/std/macro.line.html#examples) Examples --------------------------------------------------------------------------- let current_line = line!(); println!("defined on line: {current_line}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+current_line+=+line!();%0A++++println!(%22defined+on+line:+%7Bcurrent_line%7D%22);%0A%7D&edition=2024 "Run code") --- # cfg_select in std - Rust [cfg\_select](https://doc.rust-lang.org/stable/std/macro.cfg_select.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro cfg\_select Copy item path ================================ [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#240) pub macro cfg_select($($tt:tt)*) { ... } 🔬This is a nightly-only experimental API. (`cfg_select` [#115585](https://github.com/rust-lang/rust/issues/115585) ) Expand description Selects code at compile-time based on `cfg` predicates. This macro evaluates, at compile-time, a series of `cfg` predicates, selects the first that is true, and emits the code guarded by that predicate. The code guarded by other predicates is not emitted. An optional trailing `_` wildcard can be used to specify a fallback. If none of the predicates are true, a [`compile_error`](https://doc.rust-lang.org/stable/std/macro.compile_error.html "macro std::compile_error") is emitted. [§](https://doc.rust-lang.org/stable/std/macro.cfg_select.html#example) Example ------------------------------------------------------------------------------- #![feature(cfg_select)] cfg_select! { unix => { fn foo() { /* unix specific functionality */ } } target_pointer_width = "32" => { fn foo() { /* non-unix, 32-bit functionality */ } } _ => { fn foo() { /* fallback implementation */ } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(cfg_select)%5D%0A%0A%0Afn+main()+%7B%0A++++cfg_select!+%7B%0A++++++++unix+=%3E+%7B%0A++++++++++++fn+foo()+%7B+/*+unix+specific+functionality+*/+%7D%0A++++++++%7D%0A++++++++target_pointer_width+=+%2232%22+=%3E+%7B%0A++++++++++++fn+foo()+%7B+/*+non-unix,+32-bit+functionality+*/+%7D%0A++++++++%7D%0A++++++++_+=%3E+%7B%0A++++++++++++fn+foo()+%7B+/*+fallback+implementation+*/+%7D%0A++++++++%7D%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") The `cfg_select!` macro can also be used in expression position, with or without braces on the right-hand side: #![feature(cfg_select)] let _some_string = cfg_select! { unix => "With great power comes great electricity bills", _ => { "Behind every successful diet is an unwatched pizza" } }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(cfg_select)%5D%0A%0A%0Afn+main()+%7B%0A++++let+_some_string+=+cfg_select!+%7B%0A++++++++unix+=%3E+%22With+great+power+comes+great+electricity+bills%22,%0A++++++++_+=%3E+%7B+%22Behind+every+successful+diet+is+an+unwatched+pizza%22+%7D%0A++++%7D;%0A%7D&version=nightly&edition=2024 "Run code") --- # std::mem - Rust [Module mem](https://doc.rust-lang.org/stable/std/mem/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module mem Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#283) Expand description Basic functions for dealing with memory. This module contains functions for querying the size and alignment of types, initializing and manipulating memory. Macros[§](https://doc.rust-lang.org/stable/std/mem/index.html#macros) ---------------------------------------------------------------------- [offset\_of](https://doc.rust-lang.org/stable/std/mem/macro.offset_of.html "macro std::mem::offset_of") Expands to the offset in bytes of a field from the beginning of the given type. Structs[§](https://doc.rust-lang.org/stable/std/mem/index.html#structs) ------------------------------------------------------------------------ [Discriminant](https://doc.rust-lang.org/stable/std/mem/struct.Discriminant.html "struct std::mem::Discriminant") Opaque type representing the discriminant of an enum. [ManuallyDrop](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "struct std::mem::ManuallyDrop") A wrapper to inhibit the compiler from automatically calling `T`’s destructor. This wrapper is 0-cost. [Assume](https://doc.rust-lang.org/stable/std/mem/struct.Assume.html "struct std::mem::Assume") Experimental Configurable proof assumptions of [`TransmuteFrom`](https://doc.rust-lang.org/stable/std/mem/trait.TransmuteFrom.html "trait std::mem::TransmuteFrom") . [DropGuard](https://doc.rust-lang.org/stable/std/mem/struct.DropGuard.html "struct std::mem::DropGuard") Experimental Wrap a value and run a closure when dropped. Traits[§](https://doc.rust-lang.org/stable/std/mem/index.html#traits) ---------------------------------------------------------------------- [TransmuteFrom](https://doc.rust-lang.org/stable/std/mem/trait.TransmuteFrom.html "trait std::mem::TransmuteFrom") Experimental Marks that `Src` is transmutable into `Self`. Functions[§](https://doc.rust-lang.org/stable/std/mem/index.html#functions) ---------------------------------------------------------------------------- [align\_of](https://doc.rust-lang.org/stable/std/mem/fn.align_of.html "fn std::mem::align_of") Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) \-required minimum alignment of a type in bytes. [align\_of\_val](https://doc.rust-lang.org/stable/std/mem/fn.align_of_val.html "fn std::mem::align_of_val") Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) \-required minimum alignment of the type of the value that `val` points to in bytes. [discriminant](https://doc.rust-lang.org/stable/std/mem/fn.discriminant.html "fn std::mem::discriminant") Returns a value uniquely identifying the enum variant in `v`. [drop](https://doc.rust-lang.org/stable/std/mem/fn.drop.html "fn std::mem::drop") Disposes of a value. [forget](https://doc.rust-lang.org/stable/std/mem/fn.forget.html "fn std::mem::forget") Takes ownership and “forgets” about the value **without running its destructor**. [min\_align\_of](https://doc.rust-lang.org/stable/std/mem/fn.min_align_of.html "fn std::mem::min_align_of") Deprecated Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) \-required minimum alignment of a type in bytes. [min\_align\_of\_val](https://doc.rust-lang.org/stable/std/mem/fn.min_align_of_val.html "fn std::mem::min_align_of_val") Deprecated Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) \-required minimum alignment of the type of the value that `val` points to in bytes. [needs\_drop](https://doc.rust-lang.org/stable/std/mem/fn.needs_drop.html "fn std::mem::needs_drop") Returns `true` if dropping values of type `T` matters. [replace](https://doc.rust-lang.org/stable/std/mem/fn.replace.html "fn std::mem::replace") Moves `src` into the referenced `dest`, returning the previous `dest` value. [size\_of](https://doc.rust-lang.org/stable/std/mem/fn.size_of.html "fn std::mem::size_of") Returns the size of a type in bytes. [size\_of\_val](https://doc.rust-lang.org/stable/std/mem/fn.size_of_val.html "fn std::mem::size_of_val") Returns the size of the pointed-to value in bytes. [swap](https://doc.rust-lang.org/stable/std/mem/fn.swap.html "fn std::mem::swap") Swaps the values at two mutable locations, without deinitializing either one. [take](https://doc.rust-lang.org/stable/std/mem/fn.take.html "fn std::mem::take") Replaces `dest` with the default value of `T`, returning the previous `dest` value. [transmute](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html "fn std::mem::transmute") ⚠ Reinterprets the bits of a value of one type as another type. [transmute\_copy](https://doc.rust-lang.org/stable/std/mem/fn.transmute_copy.html "fn std::mem::transmute_copy") ⚠ Interprets `src` as having type `&Dst`, and then reads `src` without moving the contained value. [uninitialized](https://doc.rust-lang.org/stable/std/mem/fn.uninitialized.html "fn std::mem::uninitialized") ⚠Deprecated Bypasses Rust’s normal memory-initialization checks by pretending to produce a value of type `T`, while doing nothing at all. [zeroed](https://doc.rust-lang.org/stable/std/mem/fn.zeroed.html "fn std::mem::zeroed") ⚠ Returns the value of type `T` represented by the all-zero byte-pattern. [align\_of\_val\_raw](https://doc.rust-lang.org/stable/std/mem/fn.align_of_val_raw.html "fn std::mem::align_of_val_raw") ⚠Experimental Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) \-required minimum alignment of the type of the value that `val` points to in bytes. [conjure\_zst](https://doc.rust-lang.org/stable/std/mem/fn.conjure_zst.html "fn std::mem::conjure_zst") ⚠Experimental Create a fresh instance of the inhabited ZST type `T`. [copy](https://doc.rust-lang.org/stable/std/mem/fn.copy.html "fn std::mem::copy") Experimental Bitwise-copies a value. [forget\_unsized](https://doc.rust-lang.org/stable/std/mem/fn.forget_unsized.html "fn std::mem::forget_unsized") Experimental Like [`forget`](https://doc.rust-lang.org/stable/std/mem/fn.forget.html "fn std::mem::forget") , but also accepts unsized values. [size\_of\_val\_raw](https://doc.rust-lang.org/stable/std/mem/fn.size_of_val_raw.html "fn std::mem::size_of_val_raw") ⚠Experimental Returns the size of the pointed-to value in bytes. [variant\_count](https://doc.rust-lang.org/stable/std/mem/fn.variant_count.html "fn std::mem::variant_count") Experimental Returns the number of variants in the enum type `T`. Unions[§](https://doc.rust-lang.org/stable/std/mem/index.html#unions) ---------------------------------------------------------------------- [MaybeUninit](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html "union std::mem::MaybeUninit") A wrapper type to construct uninitialized instances of `T`. --- # try in std - Rust [try](https://doc.rust-lang.org/stable/std/macro.try.html#) ------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro try Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#510) macro_rules! try { ($expr:expr $(,)?) => { ... }; } 👎Deprecated since 1.39.0: use the `?` operator instead Expand description Unwraps a result or propagates its error. The [`?` operator](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator) was added to replace `try!` and should be used instead. Furthermore, `try` is a reserved word in Rust 2018, so if you must use it, you will need to use the [raw-identifier syntax](https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html) : `r#try`. `try!` matches the given [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . In case of the `Ok` variant, the expression has the value of the wrapped value. In case of the `Err` variant, it retrieves the inner error. `try!` then performs conversion using `From`. This provides automatic conversion between specialized errors and more general ones. The resulting error is then immediately returned. Because of the early return, `try!` can only be used in functions that return [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") . [§](https://doc.rust-lang.org/stable/std/macro.try.html#examples) Examples -------------------------------------------------------------------------- use std::io; use std::fs::File; use std::io::prelude::*; enum MyError { FileWriteError } impl From for MyError { fn from(e: io::Error) -> MyError { MyError::FileWriteError } } // The preferred method of quick returning Errors fn write_to_file_question() -> Result<(), MyError> { let mut file = File::create("my_best_friends.txt")?; file.write_all(b"This is a list of my best friends.")?; Ok(()) } // The previous method of quick returning Errors fn write_to_file_using_try() -> Result<(), MyError> { let mut file = r#try!(File::create("my_best_friends.txt")); r#try!(file.write_all(b"This is a list of my best friends.")); Ok(()) } // This is equivalent to: fn write_to_file_using_match() -> Result<(), MyError> { let mut file = r#try!(File::create("my_best_friends.txt")); match file.write_all(b"This is a list of my best friends.") { Ok(v) => v, Err(e) => return Err(From::from(e)), } Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io;%0A++++use+std::fs::File;%0A++++use+std::io::prelude::*;%0A++++%0A++++enum+MyError+%7B%0A++++++++FileWriteError%0A++++%7D%0A++++%0A++++impl+From%3Cio::Error%3E+for+MyError+%7B%0A++++++++fn+from(e:+io::Error)+-%3E+MyError+%7B%0A++++++++++++MyError::FileWriteError%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+The+preferred+method+of+quick+returning+Errors%0A++++fn+write_to_file_question()+-%3E+Result%3C(),+MyError%3E+%7B%0A++++++++let+mut+file+=+File::create(%22my_best_friends.txt%22)?;%0A++++++++file.write_all(b%22This+is+a+list+of+my+best+friends.%22)?;%0A++++++++Ok(())%0A++++%7D%0A++++%0A++++//+The+previous+method+of+quick+returning+Errors%0A++++fn+write_to_file_using_try()+-%3E+Result%3C(),+MyError%3E+%7B%0A++++++++let+mut+file+=+r%23try!(File::create(%22my_best_friends.txt%22));%0A++++++++r%23try!(file.write_all(b%22This+is+a+list+of+my+best+friends.%22));%0A++++++++Ok(())%0A++++%7D%0A++++%0A++++//+This+is+equivalent+to:%0A++++fn+write_to_file_using_match()+-%3E+Result%3C(),+MyError%3E+%7B%0A++++++++let+mut+file+=+r%23try!(File::create(%22my_best_friends.txt%22));%0A++++++++match+file.write_all(b%22This+is+a+list+of+my+best+friends.%22)+%7B%0A++++++++++++Ok(v)+=%3E+v,%0A++++++++++++Err(e)+=%3E+return+Err(From::from(e)),%0A++++++++%7D%0A++++++++Ok(())%0A++++%7D%0A%7D&edition=2024 "Run code") --- # include in std - Rust [include](https://doc.rust-lang.org/stable/std/macro.include.html#) -------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro include Copy item path ============================ 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1487) macro_rules! include { ($file:expr $(,)?) => { ... }; } Expand description Parses a file as an expression or an item according to the context. **Warning**: For multi-file Rust projects, the `include!` macro is probably not what you are looking for. Usually, multi-file Rust projects use [modules](https://doc.rust-lang.org/reference/items/modules.html) . Multi-file projects and modules are explained in the Rust-by-Example book [here](https://doc.rust-lang.org/rust-by-example/mod/split.html) and the module system is explained in the Rust Book [here](https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html) . The included file is placed in the surrounding code [unhygienically](https://doc.rust-lang.org/reference/macros-by-example.html#hygiene) . If the included file is parsed as an expression and variables or functions share names across both files, it could result in variables or functions being different from what the included file expected. The included file is located relative to the current file (similarly to how modules are found). The provided path is interpreted in a platform-specific way at compile time. So, for instance, an invocation with a Windows path containing backslashes `\` would not compile correctly on Unix. [§](https://doc.rust-lang.org/stable/std/macro.include.html#uses) Uses ---------------------------------------------------------------------- The `include!` macro is primarily used for two purposes. It is used to include documentation that is written in a separate file and it is used to include [build artifacts usually as a result from the `build.rs` script](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script) . When using the `include` macro to include stretches of documentation, remember that the included file still needs to be a valid Rust syntax. It is also possible to use the [`include_str`](https://doc.rust-lang.org/stable/std/macro.include_str.html "macro std::include_str") macro as `#![doc = include_str!("...")]` (at the module level) or `#[doc = include_str!("...")]` (at the item level) to include documentation from a plain text or markdown file. [§](https://doc.rust-lang.org/stable/std/macro.include.html#examples) Examples ------------------------------------------------------------------------------ Assume there are two files in the same directory with the following contents: File ‘monkeys.in’: [ⓘ](https://doc.rust-lang.org/stable/std/macro.include.html# "This example is not tested") ['🙈', '🙊', '🙉'] .iter() .cycle() .take(6) .collect::() [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%5B%27%F0%9F%99%88%27,+%27%F0%9F%99%8A%27,+%27%F0%9F%99%89%27%5D%0A++++++++.iter()%0A++++++++.cycle()%0A++++++++.take(6)%0A++++++++.collect::%3CString%3E()%0A%7D&edition=2024 "Run code") File ‘main.rs’: [ⓘ](https://doc.rust-lang.org/stable/std/macro.include.html# "This example is not tested") fn main() { let my_string = include!("monkeys.in"); assert_eq!("🙈🙊🙉🙈🙊🙉", my_string); println!("{my_string}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+my_string+=+include!(%22monkeys.in%22);%0A++++assert_eq!(%22%F0%9F%99%88%F0%9F%99%8A%F0%9F%99%89%F0%9F%99%88%F0%9F%99%8A%F0%9F%99%89%22,+my_string);%0A++++println!(%22%7Bmy_string%7D%22);%0A%7D&edition=2024 "Run code") Compiling ‘main.rs’ and running the resulting binary will print “🙈🙊🙉🙈🙊🙉”. --- # break - Rust [break](https://doc.rust-lang.org/stable/std/keyword.break.html#) ------------------------------------------------------------------ Keyword break Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#174) Expand description Exit early from a loop or labelled block. When `break` is encountered, execution of the associated loop body is immediately terminated. let mut last = 0; for x in 1..100 { if x > 12 { break; } last = x; } assert_eq!(last, 12); println!("{last}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+last+=+0;%0A++++%0A++++for+x+in+1..100+%7B%0A++++++++if+x+%3E+12+%7B%0A++++++++++++break;%0A++++++++%7D%0A++++++++last+=+x;%0A++++%7D%0A++++%0A++++assert_eq!(last,+12);%0A++++println!(%22%7Blast%7D%22);%0A%7D&edition=2024 "Run code") A break expression is normally associated with the innermost loop enclosing the `break` but a label can be used to specify which enclosing loop is affected. 'outer: for i in 1..=5 { println!("outer iteration (i): {i}"); '_inner: for j in 1..=200 { println!(" inner iteration (j): {j}"); if j >= 3 { // breaks from inner loop, lets outer loop continue. break; } if i >= 2 { // breaks from outer loop, and directly to "Bye". break 'outer; } } } println!("Bye."); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%27outer:+for+i+in+1..=5+%7B%0A++++++++println!(%22outer+iteration+(i):+%7Bi%7D%22);%0A++++%0A++++++++%27_inner:+for+j+in+1..=200+%7B%0A++++++++++++println!(%22++++inner+iteration+(j):+%7Bj%7D%22);%0A++++++++++++if+j+%3E=+3+%7B%0A++++++++++++++++//+breaks+from+inner+loop,+lets+outer+loop+continue.%0A++++++++++++++++break;%0A++++++++++++%7D%0A++++++++++++if+i+%3E=+2+%7B%0A++++++++++++++++//+breaks+from+outer+loop,+and+directly+to+%22Bye%22.%0A++++++++++++++++break+%27outer;%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A++++println!(%22Bye.%22);%0A%7D&edition=2024 "Run code") When associated with `loop`, a break expression may be used to return a value from that loop. This is only valid with `loop` and not with any other type of loop. If no value is specified for `break;` it returns `()`. Every `break` within a loop must return the same type. let (mut a, mut b) = (1, 1); let result = loop { if b > 10 { break b; } let c = a + b; a = b; b = c; }; // first number in Fibonacci sequence over 10: assert_eq!(result, 13); println!("{result}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+(mut+a,+mut+b)+=+(1,+1);%0A++++let+result+=+loop+%7B%0A++++++++if+b+%3E+10+%7B%0A++++++++++++break+b;%0A++++++++%7D%0A++++++++let+c+=+a+%2B+b;%0A++++++++a+=+b;%0A++++++++b+=+c;%0A++++%7D;%0A++++//+first+number+in+Fibonacci+sequence+over+10:%0A++++assert_eq!(result,+13);%0A++++println!(%22%7Bresult%7D%22);%0A%7D&edition=2024 "Run code") It is also possible to exit from any _labelled_ block returning the value early. If no value is specified for `break;` it returns `()`. let inputs = vec!["Cow", "Cat", "Dog", "Snake", "Cod"]; let mut results = vec![]; for input in inputs { let result = 'filter: { if input.len() > 3 { break 'filter Err("Too long"); }; if !input.contains("C") { break 'filter Err("No Cs"); }; Ok(input.to_uppercase()) }; results.push(result); } // [Ok("COW"), Ok("CAT"), Err("No Cs"), Err("Too long"), Ok("COD")] println!("{:?}", results) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+inputs+=+vec!%5B%22Cow%22,+%22Cat%22,+%22Dog%22,+%22Snake%22,+%22Cod%22%5D;%0A++++%0A++++let+mut+results+=+vec!%5B%5D;%0A++++for+input+in+inputs+%7B%0A++++++++let+result+=+%27filter:+%7B%0A++++++++++++if+input.len()+%3E+3+%7B%0A++++++++++++++++break+%27filter+Err(%22Too+long%22);%0A++++++++++++%7D;%0A++++%0A++++++++++++if+!input.contains(%22C%22)+%7B%0A++++++++++++++++break+%27filter+Err(%22No+Cs%22);%0A++++++++++++%7D;%0A++++%0A++++++++++++Ok(input.to_uppercase())%0A++++++++%7D;%0A++++%0A++++++++results.push(result);%0A++++%7D%0A++++%0A++++//+%5BOk(%22COW%22),+Ok(%22CAT%22),+Err(%22No+Cs%22),+Err(%22Too+long%22),+Ok(%22COD%22)%5D%0A++++println!(%22%7B:?%7D%22,+results)%0A%7D&edition=2024 "Run code") For more details consult the [Reference on “break expression”](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html#break-expressions) and the [Reference on “break and loop values”](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html#break-and-loop-values) . --- # become - Rust [become](https://doc.rust-lang.org/stable/std/keyword.become.html#) -------------------------------------------------------------------- Keyword become Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1389) Expand description Perform a tail-call of a function. `feature(explicit_tail_calls)` is currently incomplete and may not work properly. When tail calling a function, instead of its stack frame being added to the stack, the stack frame of the caller is directly replaced with the callee’s. This means that as long as a loop in a call graph only uses tail calls, the stack growth will be bounded. This is useful for writing functional-style code (since it prevents recursion from exhausting resources) or for code optimization (since a tail call _might_ be cheaper than a normal call, tail calls can be used in a similar manner to computed goto). Example of using `become` to implement functional-style `fold`: #![feature(explicit_tail_calls)] #![expect(incomplete_features)] fn fold(slice: &[T], init: S, f: impl Fn(S, T) -> S) -> S { match slice { // without `become`, on big inputs this could easily overflow the // stack. using a tail call guarantees that the stack will not grow unboundedly [first, rest @ ..] => become fold(rest, f(init, *first), f), [] => init, } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(explicit_tail_calls)%5D%0A%0A%23!%5Bexpect(incomplete_features)%5D%0A%0A%0Afn+main()+%7B%0A++++fn+fold%3CT:+Copy,+S%3E(slice:+%26%5BT%5D,+init:+S,+f:+impl+Fn(S,+T)+-%3E+S)+-%3E+S+%7B%0A++++++++match+slice+%7B%0A++++++++++++//+without+%60become%60,+on+big+inputs+this+could+easily+overflow+the%0A++++++++++++//+stack.+using+a+tail+call+guarantees+that+the+stack+will+not+grow+unboundedly%0A++++++++++++%5Bfirst,+rest+%40+..%5D+=%3E+become+fold(rest,+f(init,+*first),+f),%0A++++++++++++%5B%5D+=%3E+init,%0A++++++++%7D%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") Compilers can already perform “tail call optimization” – they can replace normal calls with tail calls, although there are no guarantees that this will be done. However, to perform TCO, the call needs to be the last thing that happens in the functions and be returned from it. This requirement is often broken by drop code for locals, which is run after computing the return expression: fn example() { let string = "meow".to_owned(); println!("{string}"); return help(); // this is *not* the last thing that happens in `example`... } // ... because it is desugared to this: fn example_desugared() { let string = "meow".to_owned(); println!("{string}"); let tmp = help(); drop(string); return tmp; } fn help() {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+example()+%7B%0A++++++++let+string+=+%22meow%22.to_owned();%0A++++++++println!(%22%7Bstring%7D%22);%0A++++++++return+help();+//+this+is+*not*+the+last+thing+that+happens+in+%60example%60...%0A++++%7D%0A++++%0A++++//+...+because+it+is+desugared+to+this:%0A++++fn+example_desugared()+%7B%0A++++++++let+string+=+%22meow%22.to_owned();%0A++++++++println!(%22%7Bstring%7D%22);%0A++++++++let+tmp+=+help();%0A++++++++drop(string);%0A++++++++return+tmp;%0A++++%7D%0A++++%0A++++fn+help()+%7B%7D%0A%7D&edition=2024 "Run code") For this reason, `become` also changes the drop order, such that locals are dropped _before_ evaluating the call. In order to guarantee that the compiler can perform a tail call, `become` currently has these requirements: 1. callee and caller must have the same ABI, arguments, and return type 2. callee and caller must not have varargs 3. caller must not be marked with `#[track_caller]` * callee is allowed to be marked with `#[track_caller]` as otherwise adding `#[track_caller]` would be a breaking change. if callee is marked with `#[track_caller]` a tail call is not guaranteed. 4. callee and caller cannot be a closure (unless it’s coerced to a function pointer) It is possible to tail-call a function pointer: #![feature(explicit_tail_calls)] #![expect(incomplete_features)] #[derive(Copy, Clone)] enum Inst { Inc, Dec } fn dispatch(stream: &[Inst], state: u32) -> u32 { const TABLE: &[fn(&[Inst], u32) -> u32] = &[increment, decrement]; match stream { [inst, rest @ ..] => become TABLE[*inst as usize](rest, state), [] => state, } } fn increment(stream: &[Inst], state: u32) -> u32 { become dispatch(stream, state + 1) } fn decrement(stream: &[Inst], state: u32) -> u32 { become dispatch(stream, state - 1) } let program = &[Inst::Inc, Inst::Inc, Inst::Dec, Inst::Inc]; assert_eq!(dispatch(program, 0), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(explicit_tail_calls)%5D%0A%0A%23!%5Bexpect(incomplete_features)%5D%0A%0A%0Afn+main()+%7B%0A++++%23%5Bderive(Copy,+Clone)%5D%0A++++enum+Inst+%7B+Inc,+Dec+%7D%0A++++%0A++++fn+dispatch(stream:+%26%5BInst%5D,+state:+u32)+-%3E+u32+%7B%0A++++++++const+TABLE:+%26%5Bfn(%26%5BInst%5D,+u32)+-%3E+u32%5D+=+%26%5Bincrement,+decrement%5D;%0A++++++++match+stream+%7B%0A++++++++++++%5Binst,+rest+%40+..%5D+=%3E+become+TABLE%5B*inst+as+usize%5D(rest,+state),%0A++++++++++++%5B%5D+=%3E+state,%0A++++++++%7D%0A++++%7D%0A++++%0A++++fn+increment(stream:+%26%5BInst%5D,+state:+u32)+-%3E+u32+%7B%0A++++++++become+dispatch(stream,+state+%2B+1)%0A++++%7D%0A++++%0A++++fn+decrement(stream:+%26%5BInst%5D,+state:+u32)+-%3E+u32+%7B%0A++++++++become+dispatch(stream,+state+-+1)%0A++++%7D%0A++++%0A++++let+program+=+%26%5BInst::Inc,+Inst::Inc,+Inst::Dec,+Inst::Inc%5D;%0A++++assert_eq!(dispatch(program,+0),+2);%0A%7D&version=nightly&edition=2024 "Run code") --- # Redirecting... Redirecting to... [ch18-02-trait-objects.html](https://doc.rust-lang.org/stable/book/ch18-02-trait-objects.html) . --- # continue - Rust [continue](https://doc.rust-lang.org/stable/std/keyword.continue.html#) ------------------------------------------------------------------------ Keyword continue Copy item path =============================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#291) Expand description Skip to the next iteration of a loop. When `continue` is encountered, the current iteration is terminated, returning control to the loop head, typically continuing with the next iteration. // Printing odd numbers by skipping even ones for number in 1..=10 { if number % 2 == 0 { continue; } println!("{number}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+Printing+odd+numbers+by+skipping+even+ones%0A++++for+number+in+1..=10+%7B%0A++++++++if+number+%25+2+==+0+%7B%0A++++++++++++continue;%0A++++++++%7D%0A++++++++println!(%22%7Bnumber%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") Like `break`, `continue` is normally associated with the innermost enclosing loop, but labels may be used to specify the affected loop. // Print Odd numbers under 30 with unit <= 5 'tens: for ten in 0..3 { '_units: for unit in 0..=9 { if unit % 2 == 0 { continue; } if unit > 5 { continue 'tens; } println!("{}", ten * 10 + unit); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+Print+Odd+numbers+under+30+with+unit+%3C=+5%0A++++%27tens:+for+ten+in+0..3+%7B%0A++++++++%27_units:+for+unit+in+0..=9+%7B%0A++++++++++++if+unit+%25+2+==+0+%7B%0A++++++++++++++++continue;%0A++++++++++++%7D%0A++++++++++++if+unit+%3E+5+%7B%0A++++++++++++++++continue+%27tens;%0A++++++++++++%7D%0A++++++++++++println!(%22%7B%7D%22,+ten+*+10+%2B+unit);%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") See [continue expressions](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html#continue-expressions) from the reference for more details. --- # concat_bytes in std - Rust [concat\_bytes](https://doc.rust-lang.org/stable/std/macro.concat_bytes.html#) ------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro concat\_bytes Copy item path ================================== [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1129) macro_rules! concat_bytes { ($($e:literal),+ $(,)?) => { ... }; } 🔬This is a nightly-only experimental API. (`concat_bytes` [#87555](https://github.com/rust-lang/rust/issues/87555) ) Expand description Concatenates literals into a byte slice. This macro takes any number of comma-separated literals, and concatenates them all into one, yielding an expression of type `&[u8; _]`, which represents all of the literals concatenated left-to-right. The literals passed can be any combination of: * byte literals (`b'r'`) * byte strings (`b"Rust"`) * arrays of bytes/numbers (`[b'A', 66, b'C']`) [§](https://doc.rust-lang.org/stable/std/macro.concat_bytes.html#examples) Examples ----------------------------------------------------------------------------------- #![feature(concat_bytes)] let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]); assert_eq!(s, b"ABCDEF"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(concat_bytes)%5D%0A%0A%0Afn+main()+%7B%0Alet+s:+%26%5Bu8;+6%5D+=+concat_bytes!(b%27A%27,+b%22BC%22,+%5B68,+b%27E%27,+70%5D);%0Aassert_eq!(s,+b%22ABCDEF%22);%0A%7D&version=nightly&edition=2024 "Run code") --- # SelfTy - Rust [SelfTy](https://doc.rust-lang.org/stable/std/keyword.SelfTy.html#) -------------------------------------------------------------------- Keyword SelfTy Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1553) Expand description The implementing type within a [`trait`](https://doc.rust-lang.org/stable/std/keyword.trait.html) or [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) block, or the current type within a type definition. Within a type definition: struct Node { elem: i32, // `Self` is a `Node` here. next: Option>, } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++struct+Node+%7B%0A++++++++elem:+i32,%0A++++++++//+%60Self%60+is+a+%60Node%60+here.%0A++++++++next:+Option%3CBox%3CSelf%3E%3E,%0A++++%7D%0A%7D&edition=2024 "Run code") In an [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) block: struct Foo(i32); impl Foo { fn new() -> Self { Self(0) } } assert_eq!(Foo::new().0, Foo(0).0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Foo(i32);%0A++++%0A++++impl+Foo+%7B%0A++++++++fn+new()+-%3E+Self+%7B%0A++++++++++++Self(0)%0A++++++++%7D%0A++++%7D%0A++++%0A++++assert_eq!(Foo::new().0,+Foo(0).0);%0A%7D&edition=2024 "Run code") Generic parameters are implicit with `Self`: struct Wrap { elem: T, } impl Wrap { fn new(elem: T) -> Self { Self { elem } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++struct+Wrap%3CT%3E+%7B%0A++++++++elem:+T,%0A++++%7D%0A++++%0A++++impl%3CT%3E+Wrap%3CT%3E+%7B%0A++++++++fn+new(elem:+T)+-%3E+Self+%7B%0A++++++++++++Self+%7B+elem+%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") In a [`trait`](https://doc.rust-lang.org/stable/std/keyword.trait.html) definition and related [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) block: trait Example { fn example() -> Self; } struct Foo(i32); impl Example for Foo { fn example() -> Self { Self(42) } } assert_eq!(Foo::example().0, Foo(42).0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Example+%7B%0A++++++++fn+example()+-%3E+Self;%0A++++%7D%0A++++%0A++++struct+Foo(i32);%0A++++%0A++++impl+Example+for+Foo+%7B%0A++++++++fn+example()+-%3E+Self+%7B%0A++++++++++++Self(42)%0A++++++++%7D%0A++++%7D%0A++++%0A++++assert_eq!(Foo::example().0,+Foo(42).0);%0A%7D&edition=2024 "Run code") --- # impl - Rust [impl](https://doc.rust-lang.org/stable/std/keyword.impl.html#) ---------------------------------------------------------------- Keyword impl Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#807) Expand description Implementations of functionality for a type, or a type implementing some functionality. There are two uses of the keyword `impl`: * An `impl` block is an item that is used to implement some functionality for a type. * An `impl Trait` in a type-position can be used to designate a type that implements a trait called `Trait`. [§](https://doc.rust-lang.org/stable/std/keyword.impl.html#implementing-functionality-for-a-type) Implementing Functionality for a Type --------------------------------------------------------------------------------------------------------------------------------------- The `impl` keyword is primarily used to define implementations on types. Inherent implementations are standalone, while trait implementations are used to implement traits for types, or other traits. An implementation consists of definitions of functions and consts. A function defined in an `impl` block can be standalone, meaning it would be called like `Vec::new()`. If the function takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using method-call syntax, a familiar feature to any object-oriented programmer, like `vec.len()`. ### [§](https://doc.rust-lang.org/stable/std/keyword.impl.html#inherent-implementations) Inherent Implementations struct Example { number: i32, } impl Example { fn boo() { println!("boo! Example::boo() was called!"); } fn answer(&mut self) { self.number += 42; } fn get_number(&self) -> i32 { self.number } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Example+%7B%0A++++++++number:+i32,%0A++++%7D%0A++++%0A++++impl+Example+%7B%0A++++++++fn+boo()+%7B%0A++++++++++++println!(%22boo!+Example::boo()+was+called!%22);%0A++++++++%7D%0A++++%0A++++++++fn+answer(%26mut+self)+%7B%0A++++++++++++self.number+%2B=+42;%0A++++++++%7D%0A++++%0A++++++++fn+get_number(%26self)+-%3E+i32+%7B%0A++++++++++++self.number%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") It matters little where an inherent implementation is defined; its functionality is in scope wherever its implementing type is. ### [§](https://doc.rust-lang.org/stable/std/keyword.impl.html#trait-implementations-1) Trait Implementations struct Example { number: i32, } trait Thingy { fn do_thingy(&self); } impl Thingy for Example { fn do_thingy(&self) { println!("doing a thing! also, number is {}!", self.number); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Example+%7B%0A++++++++number:+i32,%0A++++%7D%0A++++%0A++++trait+Thingy+%7B%0A++++++++fn+do_thingy(%26self);%0A++++%7D%0A++++%0A++++impl+Thingy+for+Example+%7B%0A++++++++fn+do_thingy(%26self)+%7B%0A++++++++++++println!(%22doing+a+thing!+also,+number+is+%7B%7D!%22,+self.number);%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") It matters little where a trait implementation is defined; its functionality can be brought into scope by importing the trait it implements. For more information on implementations, see the [Rust book](https://doc.rust-lang.org/stable/book/ch05-03-method-syntax.html) or the [Reference](https://doc.rust-lang.org/stable/reference/items/implementations.html) . [§](https://doc.rust-lang.org/stable/std/keyword.impl.html#designating-a-type-that-implements-some-functionality) Designating a Type that Implements Some Functionality ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- The other use of the `impl` keyword is in `impl Trait` syntax, which can be understood to mean “any (or some) concrete type that implements Trait”. It can be used as the type of a variable declaration, in [argument position](https://rust-lang.github.io/rfcs/1951-expand-impl-trait.html) or in [return position](https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html) . One pertinent use case is in working with closures, which have unnameable types. fn thing_returning_closure() -> impl Fn(i32) -> bool { println!("here's a closure for you!"); |x: i32| x % 3 == 0 } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+thing_returning_closure()+-%3E+impl+Fn(i32)+-%3E+bool+%7B%0A++++++++println!(%22here%27s+a+closure+for+you!%22);%0A++++++++%7Cx:+i32%7C+x+%25+3+==+0%0A++++%7D%0A%7D&edition=2024 "Run code") For more information on `impl Trait` syntax, see the [Rust book](https://doc.rust-lang.org/stable/book/ch10-02-traits.html#returning-types-that-implement-traits) . --- # crate - Rust [crate](https://doc.rust-lang.org/stable/std/keyword.crate.html#) ------------------------------------------------------------------ Keyword crate Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#328) Expand description A Rust binary or library. The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are used to specify a dependency on a crate external to the one it’s declared in. Crates are the fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can be read about crates in the [Reference](https://doc.rust-lang.org/stable/reference/items/extern-crates.html) . [ⓘ](https://doc.rust-lang.org/stable/std/keyword.crate.html# "This example is not tested") extern crate rand; extern crate my_crate as thing; extern crate std; // implicitly added to the root of every Rust project [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Aextern+crate+rand;%0Aextern+crate+my_crate+as+thing;%0Aextern+crate+std;%0Afn+main()+%7B%0A%0A%7D&edition=2024 "Run code") The `as` keyword can be used to change what the crate is referred to as in your project. If a crate name includes a dash, it is implicitly imported with the dashes replaced by underscores. `crate` can also be used as in conjunction with `pub` to signify that the item it’s attached to is public only to other members of the same crate it’s in. pub(crate) use std::io::Error as IoError; pub(crate) enum CoolMarkerType { } pub struct PublicThing { pub(crate) semi_secret_thing: bool, } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(unused_imports)%5D%0A++++pub(crate)+use+std::io::Error+as+IoError;%0A++++pub(crate)+enum+CoolMarkerType+%7B+%7D%0A++++pub+struct+PublicThing+%7B%0A++++++++pub(crate)+semi_secret_thing:+bool,%0A++++%7D%0A%7D&edition=2024 "Run code") `crate` is also used to represent the absolute path of a module, where `crate` refers to the root of the current crate. For instance, `crate::foo::bar` refers to the name `bar` inside the module `foo`, from anywhere else in the same crate. --- # if - Rust [if](https://doc.rust-lang.org/stable/std/keyword.if.html#) ------------------------------------------------------------ Keyword if Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#717) Expand description Evaluate a block if a condition holds. `if` is a familiar construct to most programmers, and is the main way you’ll often do logic in your code. However, unlike in most languages, `if` blocks can also act as expressions. if 1 == 2 { println!("whoops, mathematics broke"); } else { println!("everything's fine!"); } let greeting = if rude { "sup nerd." } else { "hello, friend!" }; if let Ok(x) = "123".parse::() { println!("{} double that and you get {}!", greeting, x * 2); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+rude+=+true;%0A++++if+1+==+2+%7B%0A++++++++println!(%22whoops,+mathematics+broke%22);%0A++++%7D+else+%7B%0A++++++++println!(%22everything%27s+fine!%22);%0A++++%7D%0A++++%0A++++let+greeting+=+if+rude+%7B%0A++++++++%22sup+nerd.%22%0A++++%7D+else+%7B%0A++++++++%22hello,+friend!%22%0A++++%7D;%0A++++%0A++++if+let+Ok(x)+=+%22123%22.parse::%3Ci32%3E()+%7B%0A++++++++println!(%22%7B%7D+double+that+and+you+get+%7B%7D!%22,+greeting,+x+*+2);%0A++++%7D%0A%7D&edition=2024 "Run code") Shown above are the three typical forms an `if` block comes in. First is the usual kind of thing you’d see in many languages, with an optional `else` block. Second uses `if` as an expression, which is only possible if all branches return the same type. An `if` expression can be used everywhere you’d expect. The third kind of `if` block is an `if let` block, which behaves similarly to using a `match` expression: if let Some(x) = Some(123) { // code } else { // something else } match Some(123) { Some(x) => { // code }, _ => { // something else }, } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++if+let+Some(x)+=+Some(123)+%7B%0A++++++++//+code%0A++++let+_+=+x;%0A++++%7D+else+%7B%0A++++++++//+something+else%0A++++%7D%0A++++%0A++++match+Some(123)+%7B%0A++++++++Some(x)+=%3E+%7B%0A++++++++++++//+code%0A++++let+_+=+x;%0A++++++++%7D,%0A++++++++_+=%3E+%7B%0A++++++++++++//+something+else%0A++++++++%7D,%0A++++%7D%0A%7D&edition=2024 "Run code") Each kind of `if` expression can be mixed and matched as needed. if true == false { println!("oh no"); } else if "something" == "other thing" { println!("oh dear"); } else if let Some(200) = "blarg".parse::().ok() { println!("uh oh"); } else { println!("phew, nothing's broken"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++if+true+==+false+%7B%0A++++++++println!(%22oh+no%22);%0A++++%7D+else+if+%22something%22+==+%22other+thing%22+%7B%0A++++++++println!(%22oh+dear%22);%0A++++%7D+else+if+let+Some(200)+=+%22blarg%22.parse::%3Ci32%3E().ok()+%7B%0A++++++++println!(%22uh+oh%22);%0A++++%7D+else+%7B%0A++++++++println!(%22phew,+nothing%27s+broken%22);%0A++++%7D%0A%7D&edition=2024 "Run code") The `if` keyword is used in one other place in Rust, namely as a part of pattern matching itself, allowing patterns such as `Some(x) if x > 200` to be used. For more information on `if` expressions, see the [Rust book](https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#if-expressions) or the [Reference](https://doc.rust-lang.org/stable/reference/expressions/if-expr.html) . --- # stringify in std - Rust [stringify](https://doc.rust-lang.org/stable/std/macro.stringify.html#) ------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro stringify Copy item path ============================== 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1278) macro_rules! stringify { ($($t:tt)*) => { ... }; } Expand description Stringifies its arguments. This macro will yield an expression of type `&'static str` which is the stringification of all the tokens passed to the macro. No restrictions are placed on the syntax of the macro invocation itself. Note that the expanded results of the input tokens may change in the future. You should be careful if you rely on the output. [§](https://doc.rust-lang.org/stable/std/macro.stringify.html#examples) Examples -------------------------------------------------------------------------------- let one_plus_one = stringify!(1 + 1); assert_eq!(one_plus_one, "1 + 1"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+one_plus_one+=+stringify!(1+%2B+1);%0A++++assert_eq!(one_plus_one,+%221+%2B+1%22);%0A%7D&edition=2024 "Run code") --- # trace_macros in std - Rust [trace\_macros](https://doc.rust-lang.org/stable/std/macro.trace_macros.html#) ------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro trace\_macros Copy item path ================================== [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1613) macro_rules! trace_macros { (true) => { ... }; (false) => { ... }; } 🔬This is a nightly-only experimental API. (`trace_macros` [#29598](https://github.com/rust-lang/rust/issues/29598) ) Expand description Enables or disables tracing functionality used for debugging other macros. --- # log_syntax in std - Rust [log\_syntax](https://doc.rust-lang.org/stable/std/macro.log_syntax.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro log\_syntax Copy item path ================================ [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1599) macro_rules! log_syntax { ($($arg:tt)*) => { ... }; } 🔬This is a nightly-only experimental API. (`log_syntax` [#29598](https://github.com/rust-lang/rust/issues/29598) ) Expand description Prints passed tokens into the standard output. --- # module_path in std - Rust [module\_path](https://doc.rust-lang.org/stable/std/macro.module_path.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro module\_path Copy item path ================================= 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1384) macro_rules! module_path { () => { ... }; } Expand description Expands to a string that represents the current module path. The current module path can be thought of as the hierarchy of modules leading back up to the crate root. The first component of the path returned is the name of the crate currently being compiled. [§](https://doc.rust-lang.org/stable/std/macro.module_path.html#examples) Examples ---------------------------------------------------------------------------------- mod test { pub fn foo() { assert!(module_path!().ends_with("test")); } } test::foo(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++mod+test+%7B%0A++++++++pub+fn+foo()+%7B%0A++++++++++++assert!(module_path!().ends_with(%22test%22));%0A++++++++%7D%0A++++%7D%0A++++%0A++++test::foo();%0A%7D&edition=2024 "Run code") --- # print in std - Rust [print](https://doc.rust-lang.org/stable/std/macro.print.html#) ---------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro print Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/macros.rs.html#82-86) macro_rules! print { ($($arg:tt)*) => { ... }; } Expand description Prints to the standard output. Equivalent to the [`println!`](https://doc.rust-lang.org/stable/std/macro.println.html "macro std::println") macro except that a newline is not printed at the end of the message. Note that stdout is frequently line-buffered by default so it may be necessary to use [`io::stdout().flush()`](https://doc.rust-lang.org/stable/std/io/trait.Write.html#tymethod.flush "method std::io::Write::flush") to ensure the output is emitted immediately. The `print!` macro will lock the standard output on each call. If you call `print!` within a hot loop, this behavior may be the bottleneck of the loop. To avoid this, lock stdout with [`io::stdout().lock()`](https://doc.rust-lang.org/stable/std/io/struct.Stdout.html "struct std::io::Stdout") : use std::io::{stdout, Write}; let mut lock = stdout().lock(); write!(lock, "hello world").unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io::%7Bstdout,+Write%7D;%0A++++%0A++++let+mut+lock+=+stdout().lock();%0A++++write!(lock,+%22hello+world%22).unwrap();%0A%7D&edition=2024 "Run code") Use `print!` only for the primary output of your program. Use [`eprint!`](https://doc.rust-lang.org/stable/std/macro.eprint.html "macro std::eprint") instead to print error and progress messages. See the formatting documentation in [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html "mod std::fmt") for details of the macro argument syntax. [§](https://doc.rust-lang.org/stable/std/macro.print.html#panics) Panics ------------------------------------------------------------------------ Panics if writing to `io::stdout()` fails. Writing to non-blocking stdout can cause an error, which will lead this macro to panic. [§](https://doc.rust-lang.org/stable/std/macro.print.html#examples) Examples ---------------------------------------------------------------------------- use std::io::{self, Write}; print!("this "); print!("will "); print!("be "); print!("on "); print!("the "); print!("same "); print!("line "); io::stdout().flush().unwrap(); print!("this string has a newline, why not choose println! instead?\n"); io::stdout().flush().unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io::%7Bself,+Write%7D;%0A++++%0A++++print!(%22this+%22);%0A++++print!(%22will+%22);%0A++++print!(%22be+%22);%0A++++print!(%22on+%22);%0A++++print!(%22the+%22);%0A++++print!(%22same+%22);%0A++++print!(%22line+%22);%0A++++%0A++++io::stdout().flush().unwrap();%0A++++%0A++++print!(%22this+string+has+a+newline,+why+not+choose+println!+instead?%5Cn%22);%0A++++%0A++++io::stdout().flush().unwrap();%0A%7D&edition=2024 "Run code") --- # thread_local in std - Rust [thread\_local](https://doc.rust-lang.org/stable/std/macro.thread_local.html#) ------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro thread\_local Copy item path ================================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#394-400) macro_rules! thread_local { () => { ... }; ($($tt:tt)+) => { ... }; } Expand description Declare a new thread local storage key of type [`std::thread::LocalKey`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") . [§](https://doc.rust-lang.org/stable/std/macro.thread_local.html#syntax) Syntax ------------------------------------------------------------------------------- The macro wraps any number of static declarations and makes them thread local. Publicity and attributes for each static are allowed. Example: use std::cell::{Cell, RefCell}; thread_local! { pub static FOO: Cell = const { Cell::new(1) }; static BAR: RefCell> = RefCell::new(vec![1.0, 2.0]); } assert_eq!(FOO.get(), 1); BAR.with_borrow(|v| assert_eq!(v[1], 2.0)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::%7BCell,+RefCell%7D;%0A++++%0A++++thread_local!+%7B%0A++++++++pub+static+FOO:+Cell%3Cu32%3E+=+const+%7B+Cell::new(1)+%7D;%0A++++%0A++++++++static+BAR:+RefCell%3CVec%3Cf32%3E%3E+=+RefCell::new(vec!%5B1.0,+2.0%5D);%0A++++%7D%0A++++%0A++++assert_eq!(FOO.get(),+1);%0A++++BAR.with_borrow(%7Cv%7C+assert_eq!(v%5B1%5D,+2.0));%0A%7D&edition=2024 "Run code") Note that only shared references (`&T`) to the inner data may be obtained, so a type such as [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") or [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") is typically used to allow mutating access. This macro supports a special `const {}` syntax that can be used when the initialization expression can be evaluated as a constant. This can enable a more efficient thread local implementation that can avoid lazy initialization. For types that do not [need to be dropped](https://doc.rust-lang.org/stable/std/mem/fn.needs_drop.html "fn std::mem::needs_drop") , this can enable an even more efficient implementation that does not need to track any additional state. use std::cell::RefCell; thread_local! { pub static FOO: RefCell> = const { RefCell::new(Vec::new()) }; } FOO.with_borrow(|v| assert_eq!(v.len(), 0)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++%0A++++thread_local!+%7B%0A++++++++pub+static+FOO:+RefCell%3CVec%3Cu32%3E%3E+=+const+%7B+RefCell::new(Vec::new())+%7D;%0A++++%7D%0A++++%0A++++FOO.with_borrow(%7Cv%7C+assert_eq!(v.len(),+0));%0A%7D&edition=2024 "Run code") See [`LocalKey` documentation](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") for more information. --- # std::num - Rust [Module num](https://doc.rust-lang.org/stable/std/num/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module num Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/num/mod.rs.html#1-28) Expand description Additional functionality for numerics. This module provides some extra types that are useful when doing numerical work. See the individual documentation for each piece for more information. Structs[§](https://doc.rust-lang.org/stable/std/num/index.html#structs) ------------------------------------------------------------------------ [NonZero](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html "struct std::num::NonZero") A value that is known not to equal zero. [ParseFloatError](https://doc.rust-lang.org/stable/std/num/struct.ParseFloatError.html "struct std::num::ParseFloatError") An error which can be returned when parsing a float. [ParseIntError](https://doc.rust-lang.org/stable/std/num/struct.ParseIntError.html "struct std::num::ParseIntError") An error which can be returned when parsing an integer. [Saturating](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html "struct std::num::Saturating") Provides intentionally-saturating arithmetic on `T`. [TryFromIntError](https://doc.rust-lang.org/stable/std/num/struct.TryFromIntError.html "struct std::num::TryFromIntError") The error type returned when a checked integral type conversion fails. [Wrapping](https://doc.rust-lang.org/stable/std/num/struct.Wrapping.html "struct std::num::Wrapping") Provides intentionally-wrapped arithmetic on `T`. Enums[§](https://doc.rust-lang.org/stable/std/num/index.html#enums) -------------------------------------------------------------------- [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") A classification of floating point numbers. [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") Enum to store the various types of errors that can cause parsing an integer to fail. Traits[§](https://doc.rust-lang.org/stable/std/num/index.html#traits) ---------------------------------------------------------------------- [ZeroablePrimitive](https://doc.rust-lang.org/stable/std/num/trait.ZeroablePrimitive.html "trait std::num::ZeroablePrimitive") Experimental A marker trait for primitive types which can be zero. Type Aliases[§](https://doc.rust-lang.org/stable/std/num/index.html#types) --------------------------------------------------------------------------- [NonZeroI8](https://doc.rust-lang.org/stable/std/num/type.NonZeroI8.html "type std::num::NonZeroI8") An [`i8`](https://doc.rust-lang.org/stable/std/primitive.i8.html "primitive i8") that is known not to equal zero. [NonZeroI16](https://doc.rust-lang.org/stable/std/num/type.NonZeroI16.html "type std::num::NonZeroI16") An [`i16`](https://doc.rust-lang.org/stable/std/primitive.i16.html "primitive i16") that is known not to equal zero. [NonZeroI32](https://doc.rust-lang.org/stable/std/num/type.NonZeroI32.html "type std::num::NonZeroI32") An [`i32`](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive i32") that is known not to equal zero. [NonZeroI64](https://doc.rust-lang.org/stable/std/num/type.NonZeroI64.html "type std::num::NonZeroI64") An [`i64`](https://doc.rust-lang.org/stable/std/primitive.i64.html "primitive i64") that is known not to equal zero. [NonZeroI128](https://doc.rust-lang.org/stable/std/num/type.NonZeroI128.html "type std::num::NonZeroI128") An [`i128`](https://doc.rust-lang.org/stable/std/primitive.i128.html "primitive i128") that is known not to equal zero. [NonZeroIsize](https://doc.rust-lang.org/stable/std/num/type.NonZeroIsize.html "type std::num::NonZeroIsize") An [`isize`](https://doc.rust-lang.org/stable/std/primitive.isize.html "primitive isize") that is known not to equal zero. [NonZeroU8](https://doc.rust-lang.org/stable/std/num/type.NonZeroU8.html "type std::num::NonZeroU8") A [`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") that is known not to equal zero. [NonZeroU16](https://doc.rust-lang.org/stable/std/num/type.NonZeroU16.html "type std::num::NonZeroU16") A [`u16`](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive u16") that is known not to equal zero. [NonZeroU32](https://doc.rust-lang.org/stable/std/num/type.NonZeroU32.html "type std::num::NonZeroU32") A [`u32`](https://doc.rust-lang.org/stable/std/primitive.u32.html "primitive u32") that is known not to equal zero. [NonZeroU64](https://doc.rust-lang.org/stable/std/num/type.NonZeroU64.html "type std::num::NonZeroU64") A [`u64`](https://doc.rust-lang.org/stable/std/primitive.u64.html "primitive u64") that is known not to equal zero. [NonZeroU128](https://doc.rust-lang.org/stable/std/num/type.NonZeroU128.html "type std::num::NonZeroU128") A [`u128`](https://doc.rust-lang.org/stable/std/primitive.u128.html "primitive u128") that is known not to equal zero. [NonZeroUsize](https://doc.rust-lang.org/stable/std/num/type.NonZeroUsize.html "type std::num::NonZeroUsize") A [`usize`](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") that is known not to equal zero. --- # await - Rust [await](https://doc.rust-lang.org/stable/std/keyword.await.html#) ------------------------------------------------------------------ Keyword await Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2644) Expand description Suspend execution until the result of a [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") is ready. `.await`ing a future will suspend the current function’s execution until the executor has run the future to completion. Read the [async book](https://rust-lang.github.io/async-book/) for details on how [`async`](https://doc.rust-lang.org/stable/std/keyword.async.html) /`await` and executors work. ### [§](https://doc.rust-lang.org/stable/std/keyword.await.html#editions) Editions `await` is a keyword from the 2018 edition onwards. It is available for use in stable Rust from version 1.39 onwards. --- # dyn - Rust [dyn](https://doc.rust-lang.org/stable/std/keyword.dyn.html#) -------------------------------------------------------------- Keyword dyn Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2680) Expand description `dyn` is a prefix of a [trait object](https://doc.rust-lang.org/stable/book/ch17-02-trait-objects.html) ’s type. The `dyn` keyword is used to highlight that calls to methods on the associated `Trait` are [dynamically dispatched](https://en.wikipedia.org/wiki/Dynamic_dispatch) . To use the trait this way, it must be _dyn compatible_[1](https://doc.rust-lang.org/stable/std/keyword.dyn.html#fn1) . Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that is being passed. That is, the type has been [erased](https://en.wikipedia.org/wiki/Type_erasure) . As such, a `dyn Trait` reference contains _two_ pointers. One pointer goes to the data (e.g., an instance of a struct). Another pointer goes to a map of method call names to function pointers (known as a virtual method table or vtable). At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get the function pointer and then that function pointer is called. See the Reference for more information on [trait objects](https://doc.rust-lang.org/stable/reference/types/trait-object.html) and [dyn compatibility](https://doc.rust-lang.org/stable/reference/items/traits.html#dyn-compatibility) . ### [§](https://doc.rust-lang.org/stable/std/keyword.dyn.html#trade-offs) Trade-offs The above indirection is the additional runtime cost of calling a function on a `dyn Trait`. Methods called by dynamic dispatch generally cannot be inlined by the compiler. However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as the method won’t be duplicated for each concrete type. * * * 1. Formerly known as _object safe_. [↩](https://doc.rust-lang.org/stable/std/keyword.dyn.html#fnref1) --- # false - Rust [false](https://doc.rust-lang.org/stable/std/keyword.false.html#) ------------------------------------------------------------------ Keyword false Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#494) Expand description A value of type [`bool`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") representing logical **false**. `false` is the logical opposite of [`true`](https://doc.rust-lang.org/stable/std/keyword.true.html) . See the documentation for [`true`](https://doc.rust-lang.org/stable/std/keyword.true.html) for more information. --- # extern - Rust [extern](https://doc.rust-lang.org/stable/std/keyword.extern.html#) -------------------------------------------------------------------- Keyword extern Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#483) Expand description Link to or import external code. The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`](https://doc.rust-lang.org/stable/std/keyword.crate.html) keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate lazy_static;`. The other use is in foreign function interfaces (FFI). `extern` is used in two different contexts within FFI. The first is in the form of external blocks, for declaring function interfaces that Rust code can call foreign code by. This use of `extern` is unsafe, since we are asserting to the compiler that all function declarations are correct. If they are not, using these items may lead to undefined behavior. [ⓘ](https://doc.rust-lang.org/stable/std/keyword.extern.html# "This example is not tested") // SAFETY: The function declarations given below are in // line with the header files of `my_c_library`. #[link(name = "my_c_library")] unsafe extern "C" { fn my_c_function(x: i32) -> bool; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+SAFETY:+The+function+declarations+given+below+are+in%0A++++//+line+with+the+header+files+of+%60my_c_library%60.%0A++++%23%5Blink(name+=+%22my_c_library%22)%5D%0A++++unsafe+extern+%22C%22+%7B%0A++++++++fn+my_c_function(x:+i32)+-%3E+bool;%0A++++%7D%0A%7D&edition=2024 "Run code") This code would attempt to link with `libmy_c_library.so` on unix-like systems and `my_c_library.dll` on Windows at runtime, and panic if it can’t find something to link to. Rust code could then use `my_c_function` as if it were any other unsafe Rust function. Working with non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs. The mirror use case of FFI is also done via the `extern` keyword: #[unsafe(no_mangle)] pub extern "C" fn callable_from_c(x: i32) -> bool { x % 3 == 0 } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bunsafe(no_mangle)%5D%0A++++pub+extern+%22C%22+fn+callable_from_c(x:+i32)+-%3E+bool+%7B%0A++++++++x+%25+3+==+0%0A++++%7D%0A%7D&edition=2024 "Run code") If compiled as a dylib, the resulting .so could then be linked to from a C library, and the function could be used as if it was from any other library. For more information on FFI, check the [Rust book](https://doc.rust-lang.org/stable/book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code) or the [Reference](https://doc.rust-lang.org/stable/reference/items/external-blocks.html) . --- # in - Rust [in](https://doc.rust-lang.org/stable/std/keyword.in.html#) ------------------------------------------------------------ Keyword in Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#839) Expand description Iterate over a series of values with [`for`](https://doc.rust-lang.org/stable/std/keyword.for.html) . The expression immediately following `in` must implement the [`IntoIterator`](https://doc.rust-lang.org/stable/book/ch13-04-performance.html) trait. ### [§](https://doc.rust-lang.org/stable/std/keyword.in.html#literal-examples) Literal Examples: * `for _ in 1..3 {}` - Iterate over an exclusive range up to but excluding 3. * `for _ in 1..=3 {}` - Iterate over an inclusive range up to and including 3. (Read more about [range patterns](https://doc.rust-lang.org/stable/reference/patterns.html?highlight=range#range-patterns) ) The other use of `in` is with the keyword `pub`. It allows users to declare an item as visible only within a given scope. ### [§](https://doc.rust-lang.org/stable/std/keyword.in.html#literal-example) Literal Example: * `pub(in crate::outer_mod) fn outer_mod_visible_fn() {}` - fn is visible in `outer_mod` Starting with the 2018 edition, paths for `pub(in path)` must start with `crate`, `self` or `super`. The 2015 edition may also use paths starting with `::` or modules from the crate root. For more information, see the [Reference](https://doc.rust-lang.org/stable/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself) . --- # unimplemented in std - Rust [unimplemented](https://doc.rust-lang.org/stable/std/macro.unimplemented.html#) -------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro unimplemented Copy item path ================================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#797) macro_rules! unimplemented { () => { ... }; ($($arg:tt)+) => { ... }; } Expand description Indicates unimplemented code by panicking with a message of “not implemented”. This allows your code to type-check, which is useful if you are prototyping or implementing a trait that requires multiple methods which you don’t plan to use all of. The difference between `unimplemented!` and [`todo!`](https://doc.rust-lang.org/stable/std/macro.todo.html "macro std::todo") is that while `todo!` conveys an intent of implementing the functionality later and the message is “not yet implemented”, `unimplemented!` makes no such claims. Its message is “not implemented”. Also, some IDEs will mark `todo!`s. [§](https://doc.rust-lang.org/stable/std/macro.unimplemented.html#panics) Panics -------------------------------------------------------------------------------- This will always [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") because `unimplemented!` is just a shorthand for `panic!` with a fixed, specific message. Like `panic!`, this macro has a second form for displaying custom values. [§](https://doc.rust-lang.org/stable/std/macro.unimplemented.html#examples) Examples ------------------------------------------------------------------------------------ Say we have a trait `Foo`: trait Foo { fn bar(&self) -> u8; fn baz(&self); fn qux(&self) -> Result; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Foo+%7B%0A++++++++fn+bar(%26self)+-%3E+u8;%0A++++++++fn+baz(%26self);%0A++++++++fn+qux(%26self)+-%3E+Result%3Cu64,+()%3E;%0A++++%7D%0A%7D&edition=2024 "Run code") We want to implement `Foo` for ‘MyStruct’, but for some reason it only makes sense to implement the `bar()` function. `baz()` and `qux()` will still need to be defined in our implementation of `Foo`, but we can use `unimplemented!` in their definitions to allow our code to compile. We still want to have our program stop running if the unimplemented methods are reached. struct MyStruct; impl Foo for MyStruct { fn bar(&self) -> u8 { 1 + 1 } fn baz(&self) { // It makes no sense to `baz` a `MyStruct`, so we have no logic here // at all. // This will display "thread 'main' panicked at 'not implemented'". unimplemented!(); } fn qux(&self) -> Result { // We have some logic here, // We can add a message to unimplemented! to display our omission. // This will display: // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'". unimplemented!("MyStruct isn't quxable"); } } fn main() { let s = MyStruct; s.bar(); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Atrait+Foo+%7B%0A++++fn+bar(%26self)+-%3E+u8;%0A++++fn+baz(%26self);%0A++++fn+qux(%26self)+-%3E+Result%3Cu64,+()%3E;%0A%7D%0Astruct+MyStruct;%0A%0Aimpl+Foo+for+MyStruct+%7B%0A++++fn+bar(%26self)+-%3E+u8+%7B%0A++++++++1+%2B+1%0A++++%7D%0A%0A++++fn+baz(%26self)+%7B%0A++++++++//+It+makes+no+sense+to+%60baz%60+a+%60MyStruct%60,+so+we+have+no+logic+here%0A++++++++//+at+all.%0A++++++++//+This+will+display+%22thread+%27main%27+panicked+at+%27not+implemented%27%22.%0A++++++++unimplemented!();%0A++++%7D%0A%0A++++fn+qux(%26self)+-%3E+Result%3Cu64,+()%3E+%7B%0A++++++++//+We+have+some+logic+here,%0A++++++++//+We+can+add+a+message+to+unimplemented!+to+display+our+omission.%0A++++++++//+This+will+display:%0A++++++++//+%22thread+%27main%27+panicked+at+%27not+implemented:+MyStruct+isn%27t+quxable%27%22.%0A++++++++unimplemented!(%22MyStruct+isn%27t+quxable%22);%0A++++%7D%0A%7D%0A%0Afn+main()+%7B%0A++++let+s+=+MyStruct;%0A++++s.bar();%0A%7D&edition=2024 "Run code") --- # vec in std - Rust [vec](https://doc.rust-lang.org/stable/std/macro.vec.html#) ------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro vec Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/macros.rs.html#42) macro_rules! vec { () => { ... }; ($elem:expr; $n:expr) => { ... }; ($($x:expr),+ $(,)?) => { ... }; } Expand description Creates a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") containing the arguments. `vec!` allows `Vec`s to be defined with the same syntax as array expressions. There are two forms of this macro: * Create a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") containing a given list of elements: let v = vec![1, 2, 3]; assert_eq!(v[0], 1); assert_eq!(v[1], 2); assert_eq!(v[2], 3); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v+=+vec!%5B1,+2,+3%5D;%0A++++assert_eq!(v%5B0%5D,+1);%0A++++assert_eq!(v%5B1%5D,+2);%0A++++assert_eq!(v%5B2%5D,+3);%0A%7D&edition=2024 "Run code") * Create a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") from a given element and size: let v = vec![1; 3]; assert_eq!(v, [1, 1, 1]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+v+=+vec!%5B1;+3%5D;%0A++++assert_eq!(v,+%5B1,+1,+1%5D);%0A%7D&edition=2024 "Run code") Note that unlike array expressions this syntax supports all elements which implement [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") and the number of elements doesn’t have to be a constant. This will use `clone` to duplicate an expression, so one should be careful using this with types having a nonstandard `Clone` implementation. For example, `vec![Rc::new(1); 5]` will create a vector of five references to the same boxed integer value, not five references pointing to independently boxed integers. Also, note that `vec![expr; 0]` is allowed, and produces an empty vector. This will still evaluate `expr`, however, and immediately drop the resulting value, so be mindful of side effects. --- # unreachable in std - Rust [unreachable](https://doc.rust-lang.org/stable/std/macro.unreachable.html#) ---------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro unreachable Copy item path ================================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#711) macro_rules! unreachable { ($($arg:tt)*) => { ... }; } Expand description Indicates unreachable code. This is useful any time that the compiler can’t determine that some code is unreachable. For example: * Match arms with guard conditions. * Loops that dynamically terminate. * Iterators that dynamically terminate. If the determination that the code is unreachable proves incorrect, the program immediately terminates with a [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") . The unsafe counterpart of this macro is the [`unreachable_unchecked`](https://doc.rust-lang.org/stable/std/hint/fn.unreachable_unchecked.html "fn std::hint::unreachable_unchecked") function, which will cause undefined behavior if the code is reached. [§](https://doc.rust-lang.org/stable/std/macro.unreachable.html#panics) Panics ------------------------------------------------------------------------------ This will always [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") because `unreachable!` is just a shorthand for `panic!` with a fixed, specific message. Like `panic!`, this macro has a second form for displaying custom values. [§](https://doc.rust-lang.org/stable/std/macro.unreachable.html#examples) Examples ---------------------------------------------------------------------------------- Match arms: fn foo(x: Option) { match x { Some(n) if n >= 0 => println!("Some(Non-negative)"), Some(n) if n < 0 => println!("Some(Negative)"), Some(_) => unreachable!(), // compile error if commented out None => println!("None") } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(dead_code)%5D%0A++++fn+foo(x:+Option%3Ci32%3E)+%7B%0A++++++++match+x+%7B%0A++++++++++++Some(n)+if+n+%3E=+0+=%3E+println!(%22Some(Non-negative)%22),%0A++++++++++++Some(n)+if+n+%3C++0+=%3E+println!(%22Some(Negative)%22),%0A++++++++++++Some(_)+++++++++++=%3E+unreachable!(),+//+compile+error+if+commented+out%0A++++++++++++None++++++++++++++=%3E+println!(%22None%22)%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Iterators: fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3 for i in 0.. { if 3*i < i { panic!("u32 overflow"); } if x < 3*i { return i-1; } } unreachable!("The loop should always return"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(dead_code)%5D%0A++++fn+divide_by_three(x:+u32)+-%3E+u32+%7B+//+one+of+the+poorest+implementations+of+x/3%0A++++++++for+i+in+0..+%7B%0A++++++++++++if+3*i+%3C+i+%7B+panic!(%22u32+overflow%22);+%7D%0A++++++++++++if+x+%3C+3*i+%7B+return+i-1;+%7D%0A++++++++%7D%0A++++++++unreachable!(%22The+loop+should+always+return%22);%0A++++%7D%0A%7D&edition=2024 "Run code") --- # match - Rust [match](https://doc.rust-lang.org/stable/std/keyword.match.html#) ------------------------------------------------------------------ Keyword match Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1002) Expand description Control flow based on pattern matching. `match` can be used to run code conditionally. Every pattern must be handled exhaustively either explicitly or by using wildcards like `_` in the `match`. Since `match` is an expression, values can also be returned. let opt = Option::None::; let x = match opt { Some(int) => int, None => 10, }; assert_eq!(x, 10); let a_number = Option::Some(10); match a_number { Some(x) if x <= 5 => println!("0 to 5 num = {x}"), Some(x @ 6..=10) => println!("6 to 10 num = {x}"), None => panic!(), // all other numbers _ => panic!(), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+opt+=+Option::None::%3Cusize%3E;%0A++++let+x+=+match+opt+%7B%0A++++++++Some(int)+=%3E+int,%0A++++++++None+=%3E+10,%0A++++%7D;%0A++++assert_eq!(x,+10);%0A++++%0A++++let+a_number+=+Option::Some(10);%0A++++match+a_number+%7B%0A++++++++Some(x)+if+x+%3C=+5+=%3E+println!(%220+to+5+num+=+%7Bx%7D%22),%0A++++++++Some(x+%40+6..=10)+=%3E+println!(%226+to+10+num+=+%7Bx%7D%22),%0A++++++++None+=%3E+panic!(),%0A++++++++//+all+other+numbers%0A++++++++_+=%3E+panic!(),%0A++++%7D%0A%7D&edition=2024 "Run code") `match` can be used to gain access to the inner members of an enum and use them directly. enum Outer { Double(Option, Option), Single(Option), Empty } let get_inner = Outer::Double(None, Some(String::new())); match get_inner { Outer::Double(None, Some(st)) => println!("{st}"), Outer::Single(opt) => println!("{opt:?}"), _ => panic!(), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+Outer+%7B%0A++++++++Double(Option%3Cu8%3E,+Option%3CString%3E),%0A++++++++Single(Option%3Cu8%3E),%0A++++++++Empty%0A++++%7D%0A++++%0A++++let+get_inner+=+Outer::Double(None,+Some(String::new()));%0A++++match+get_inner+%7B%0A++++++++Outer::Double(None,+Some(st))+=%3E+println!(%22%7Bst%7D%22),%0A++++++++Outer::Single(opt)+=%3E+println!(%22%7Bopt:?%7D%22),%0A++++++++_+=%3E+panic!(),%0A++++%7D%0A%7D&edition=2024 "Run code") For more information on `match` and matching in general, see the [Reference](https://doc.rust-lang.org/stable/reference/expressions/match-expr.html) . --- # const_format_args in std - Rust [const\_format\_args](https://doc.rust-lang.org/stable/std/macro.const_format_args.html#) ------------------------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) Macro const\_format\_args Copy item path ======================================== [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1011) macro_rules! const_format_args { ($fmt:expr) => { ... }; ($fmt:expr, $($args:tt)*) => { ... }; } 🔬This is a nightly-only experimental API. (`const_format_args`) Expand description Same as [`format_args`](https://doc.rust-lang.org/stable/std/macro.format_args.html "macro std::format_args") , but can be used in some const contexts. This macro is used by the panic macros for the `const_panic` feature. This macro will be removed once `format_args` is allowed in const contexts. --- # write in std - Rust [write](https://doc.rust-lang.org/stable/std/macro.write.html#) ---------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro write Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#610) macro_rules! write { ($dst:expr, $($arg:tt)*) => { ... }; } Expand description Writes formatted data into a buffer. This macro accepts a ‘writer’, a format string, and a list of arguments. Arguments will be formatted according to the specified format string and the result will be passed to the writer. The writer may be any value with a `write_fmt` method; generally this comes from an implementation of either the [`fmt::Write`](https://doc.rust-lang.org/stable/std/fmt/trait.Write.html "trait std::fmt::Write") or the [`io::Write`](https://doc.rust-lang.org/stable/std/io/trait.Write.html) trait. The macro returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") , or an [`io::Result`](https://doc.rust-lang.org/stable/std/io/type.Result.html) . See [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) for more information on the format string syntax. [§](https://doc.rust-lang.org/stable/std/macro.write.html#examples) Examples ---------------------------------------------------------------------------- use std::io::Write; fn main() -> std::io::Result<()> { let mut w = Vec::new(); write!(&mut w, "test")?; write!(&mut w, "formatted {}", "arguments")?; assert_eq!(w, b"testformatted arguments"); Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::io::Write;%0A%0Afn+main()+-%3E+std::io::Result%3C()%3E+%7B%0A++++let+mut+w+=+Vec::new();%0A++++write!(%26mut+w,+%22test%22)?;%0A++++write!(%26mut+w,+%22formatted+%7B%7D%22,+%22arguments%22)?;%0A%0A++++assert_eq!(w,+b%22testformatted+arguments%22);%0A++++Ok(())%0A%7D&edition=2024 "Run code") A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects implementing either, as objects do not typically implement both. However, the module must avoid conflict between the trait names, such as by importing them as `_` or otherwise renaming them: use std::fmt::Write as _; use std::io::Write as _; fn main() -> Result<(), Box> { let mut s = String::new(); let mut v = Vec::new(); write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt assert_eq!(v, b"s = \"abc 123\""); Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::fmt::Write+as+_;%0Ause+std::io::Write+as+_;%0A%0Afn+main()+-%3E+Result%3C(),+Box%3Cdyn+std::error::Error%3E%3E+%7B%0A++++let+mut+s+=+String::new();%0A++++let+mut+v+=+Vec::new();%0A%0A++++write!(%26mut+s,+%22%7B%7D+%7B%7D%22,+%22abc%22,+123)?;+//+uses+fmt::Write::write_fmt%0A++++write!(%26mut+v,+%22s+=+%7B:?%7D%22,+s)?;+//+uses+io::Write::write_fmt%0A++++assert_eq!(v,+b%22s+=+%5C%22abc+123%5C%22%22);%0A++++Ok(())%0A%7D&edition=2024 "Run code") If you also need the trait names themselves, such as to implement one or both on your types, import the containing module and then name them with a prefix: use std::fmt::{self, Write as _}; use std::io::{self, Write as _}; struct Example; impl fmt::Write for Example { fn write_str(&mut self, _s: &str) -> core::fmt::Result { unimplemented!(); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_imports)%5D%0A%0Afn+main()+%7B%0A++++use+std::fmt::%7Bself,+Write+as+_%7D;%0A++++use+std::io::%7Bself,+Write+as+_%7D;%0A++++%0A++++struct+Example;%0A++++%0A++++impl+fmt::Write+for+Example+%7B%0A++++++++fn+write_str(%26mut+self,+_s:+%26str)+-%3E+core::fmt::Result+%7B%0A+++++++++++++unimplemented!();%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Note: This macro can be used in `no_std` setups as well. In a `no_std` setup you are responsible for the implementation details of the components. use core::fmt::Write; struct Example; impl Write for Example { fn write_str(&mut self, _s: &str) -> core::fmt::Result { unimplemented!(); } } let mut m = Example{}; write!(&mut m, "Hello World").expect("Not written"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+core::fmt::Write;%0A++++%0A++++struct+Example;%0A++++%0A++++impl+Write+for+Example+%7B%0A++++++++fn+write_str(%26mut+self,+_s:+%26str)+-%3E+core::fmt::Result+%7B%0A+++++++++++++unimplemented!();%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+mut+m+=+Example%7B%7D;%0A++++write!(%26mut+m,+%22Hello+World%22).expect(%22Not+written%22);%0A%7D&edition=2024 "Run code") --- # else - Rust [else](https://doc.rust-lang.org/stable/std/keyword.else.html#) ---------------------------------------------------------------- Keyword else Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#381) Expand description What expression to evaluate when an [`if`](https://doc.rust-lang.org/stable/std/keyword.if.html) condition evaluates to [`false`](https://doc.rust-lang.org/stable/std/keyword.false.html) . `else` expressions are optional. When no else expressions are supplied it is assumed to evaluate to the unit type `()`. The type that the `else` blocks evaluate to must be compatible with the type that the `if` block evaluates to. As can be seen below, `else` must be followed by either: `if`, `if let`, or a block `{}` and it will return the value of that expression. let result = if true == false { "oh no" } else if "something" == "other thing" { "oh dear" } else if let Some(200) = "blarg".parse::().ok() { "uh oh" } else { println!("Sneaky side effect."); "phew, nothing's broken" }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+result+=+if+true+==+false+%7B%0A++++++++%22oh+no%22%0A++++%7D+else+if+%22something%22+==+%22other+thing%22+%7B%0A++++++++%22oh+dear%22%0A++++%7D+else+if+let+Some(200)+=+%22blarg%22.parse::%3Ci32%3E().ok()+%7B%0A++++++++%22uh+oh%22%0A++++%7D+else+%7B%0A++++++++println!(%22Sneaky+side+effect.%22);%0A++++++++%22phew,+nothing%27s+broken%22%0A++++%7D;%0A%7D&edition=2024 "Run code") Here’s another example but here we do not try and return an expression: if true == false { println!("oh no"); } else if "something" == "other thing" { println!("oh dear"); } else if let Some(200) = "blarg".parse::().ok() { println!("uh oh"); } else { println!("phew, nothing's broken"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++if+true+==+false+%7B%0A++++++++println!(%22oh+no%22);%0A++++%7D+else+if+%22something%22+==+%22other+thing%22+%7B%0A++++++++println!(%22oh+dear%22);%0A++++%7D+else+if+let+Some(200)+=+%22blarg%22.parse::%3Ci32%3E().ok()+%7B%0A++++++++println!(%22uh+oh%22);%0A++++%7D+else+%7B%0A++++++++println!(%22phew,+nothing%27s+broken%22);%0A++++%7D%0A%7D&edition=2024 "Run code") The above is _still_ an expression but it will always evaluate to `()`. There is possibly no limit to the number of `else` blocks that could follow an `if` expression however if you have several then a [`match`](https://doc.rust-lang.org/stable/std/keyword.match.html) expression might be preferable. Read more about control flow in the [Rust Book](https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#handling-multiple-conditions-with-else-if) . --- # option_env in std - Rust [option\_env](https://doc.rust-lang.org/stable/std/macro.option_env.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro option\_env Copy item path ================================ 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#1102) macro_rules! option_env { ($name:expr $(,)?) => { ... }; } Expand description Optionally inspects an environment variable at compile time. If the named environment variable is present at compile time, this will expand into an expression of type `Option<&'static str>` whose value is `Some` of the value of the environment variable (a compilation error will be emitted if the environment variable is not a valid Unicode string). If the environment variable is not present, then this will expand to `None`. See [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") for more information on this type. Use [`std::env::var`](https://doc.rust-lang.org/stable/std/env/fn.var.html) instead if you want to read the value at runtime. A compile time error is only emitted when using this macro if the environment variable exists and is not a valid Unicode string. To also emit a compile error if the environment variable is not present, use the [`env!`](https://doc.rust-lang.org/stable/std/macro.env.html "macro std::env") macro instead. [§](https://doc.rust-lang.org/stable/std/macro.option_env.html#examples) Examples --------------------------------------------------------------------------------- let key: Option<&'static str> = option_env!("SECRET_KEY"); println!("the secret key might be: {key:?}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+key:+Option%3C%26%27static+str%3E+=+option_env!(%22SECRET_KEY%22);%0A++++println!(%22the+secret+key+might+be:+%7Bkey:?%7D%22);%0A%7D&edition=2024 "Run code") --- # writeln in std - Rust [writeln](https://doc.rust-lang.org/stable/std/macro.writeln.html#) -------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro writeln Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#645) macro_rules! writeln { ($dst:expr $(,)?) => { ... }; ($dst:expr, $($arg:tt)*) => { ... }; } Expand description Writes formatted data into a buffer, with a newline appended. On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone (no additional CARRIAGE RETURN (`\r`/`U+000D`). For more information, see [`write!`](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") . For information on the format string syntax, see [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) . [§](https://doc.rust-lang.org/stable/std/macro.writeln.html#examples) Examples ------------------------------------------------------------------------------ use std::io::{Write, Result}; fn main() -> Result<()> { let mut w = Vec::new(); writeln!(&mut w)?; writeln!(&mut w, "test")?; writeln!(&mut w, "formatted {}", "arguments")?; assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes()); Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::io::%7BWrite,+Result%7D;%0A%0Afn+main()+-%3E+Result%3C()%3E+%7B%0A++++let+mut+w+=+Vec::new();%0A++++writeln!(%26mut+w)?;%0A++++writeln!(%26mut+w,+%22test%22)?;%0A++++writeln!(%26mut+w,+%22formatted+%7B%7D%22,+%22arguments%22)?;%0A%0A++++assert_eq!(%26w%5B..%5D,+%22%5Cntest%5Cnformatted+arguments%5Cn%22.as_bytes());%0A++++Ok(())%0A%7D&edition=2024 "Run code") --- # todo in std - Rust [todo](https://doc.rust-lang.org/stable/std/macro.todo.html#) -------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro todo Copy item path ========================= 1.40.0 · [Source](https://doc.rust-lang.org/stable/src/core/macros/mod.rs.html#877) macro_rules! todo { () => { ... }; ($($arg:tt)+) => { ... }; } Expand description Indicates unfinished code. This can be useful if you are prototyping and just want a placeholder to let your code pass type analysis. The difference between [`unimplemented!`](https://doc.rust-lang.org/stable/std/macro.unimplemented.html "macro std::unimplemented") and `todo!` is that while `todo!` conveys an intent of implementing the functionality later and the message is “not yet implemented”, `unimplemented!` makes no such claims. Its message is “not implemented”. Also, some IDEs will mark `todo!`s. [§](https://doc.rust-lang.org/stable/std/macro.todo.html#panics) Panics ----------------------------------------------------------------------- This will always [`panic!`](https://doc.rust-lang.org/stable/core/macro.panic.html "macro core::panic") because `todo!` is just a shorthand for `panic!` with a fixed, specific message. Like `panic!`, this macro has a second form for displaying custom values. [§](https://doc.rust-lang.org/stable/std/macro.todo.html#examples) Examples --------------------------------------------------------------------------- Here’s an example of some in-progress code. We have a trait `Foo`: trait Foo { fn bar(&self) -> u8; fn baz(&self); fn qux(&self) -> Result; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Foo+%7B%0A++++++++fn+bar(%26self)+-%3E+u8;%0A++++++++fn+baz(%26self);%0A++++++++fn+qux(%26self)+-%3E+Result%3Cu64,+()%3E;%0A++++%7D%0A%7D&edition=2024 "Run code") We want to implement `Foo` on one of our types, but we also want to work on just `bar()` first. In order for our code to compile, we need to implement `baz()` and `qux()`, so we can use `todo!`: struct MyStruct; impl Foo for MyStruct { fn bar(&self) -> u8 { 1 + 1 } fn baz(&self) { // Let's not worry about implementing baz() for now todo!(); } fn qux(&self) -> Result { // We can add a message to todo! to display our omission. // This will display: // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'". todo!("MyStruct is not yet quxable"); } } fn main() { let s = MyStruct; s.bar(); // We aren't even using baz() or qux(), so this is fine. } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Atrait+Foo+%7B%0A++++fn+bar(%26self)+-%3E+u8;%0A++++fn+baz(%26self);%0A++++fn+qux(%26self)+-%3E+Result%3Cu64,+()%3E;%0A%7D%0Astruct+MyStruct;%0A%0Aimpl+Foo+for+MyStruct+%7B%0A++++fn+bar(%26self)+-%3E+u8+%7B%0A++++++++1+%2B+1%0A++++%7D%0A%0A++++fn+baz(%26self)+%7B%0A++++++++//+Let%27s+not+worry+about+implementing+baz()+for+now%0A++++++++todo!();%0A++++%7D%0A%0A++++fn+qux(%26self)+-%3E+Result%3Cu64,+()%3E+%7B%0A++++++++//+We+can+add+a+message+to+todo!+to+display+our+omission.%0A++++++++//+This+will+display:%0A++++++++//+%22thread+%27main%27+panicked+at+%27not+yet+implemented:+MyStruct+is+not+yet+quxable%27%22.%0A++++++++todo!(%22MyStruct+is+not+yet+quxable%22);%0A++++%7D%0A%7D%0A%0Afn+main()+%7B%0A++++let+s+=+MyStruct;%0A++++s.bar();%0A%0A++++//+We+aren%27t+even+using+baz()+or+qux(),+so+this+is+fine.%0A%7D&edition=2024 "Run code") --- # as - Rust [as](https://doc.rust-lang.org/stable/std/keyword.as.html#) ------------------------------------------------------------ Keyword as Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#76) Expand description Cast between types, rename an import, or qualify paths to associated items. [§](https://doc.rust-lang.org/stable/std/keyword.as.html#type-casting) Type casting ----------------------------------------------------------------------------------- `as` is most commonly used to turn primitive types into other primitive types, but it has other uses that include turning pointers into addresses, addresses into pointers, and pointers into other pointers. let thing1: u8 = 89.0 as u8; assert_eq!('B' as u32, 66); assert_eq!(thing1 as char, 'Y'); let thing2: f32 = thing1 as f32 + 10.5; assert_eq!(true as u8 + thing2 as u8, 100); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+thing1:+u8+=+89.0+as+u8;%0A++++assert_eq!(%27B%27+as+u32,+66);%0A++++assert_eq!(thing1+as+char,+%27Y%27);%0A++++let+thing2:+f32+=+thing1+as+f32+%2B+10.5;%0A++++assert_eq!(true+as+u8+%2B+thing2+as+u8,+100);%0A%7D&edition=2024 "Run code") In general, any cast that can be performed via ascribing the type can also be done using `as`, so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (note: `let x: u32 = 123` would be best in that situation). The same is not true in the other direction, however; explicitly using `as` allows a few more coercions that aren’t allowed implicitly, such as changing the type of a raw pointer or turning closures into raw pointers. `as` can be seen as the primitive for `From` and `Into`: `as` only works with primitives (`u8`, `bool`, `str`, pointers, …) whereas `From` and `Into` also works with types like `String` or `Vec`. `as` can also be used with the `_` placeholder when the destination type can be inferred. Note that this can cause inference breakage and usually such code should use an explicit type for both clarity and stability. This is most useful when converting pointers using `as *const _` or `as *mut _` though the [`cast`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.cast "method pointer::cast") method is recommended over `as *const _` and it is [the same](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.cast-1) for `as *mut _`: those methods make the intent clearer. [§](https://doc.rust-lang.org/stable/std/keyword.as.html#renaming-imports) Renaming imports ------------------------------------------------------------------------------------------- `as` is also used to rename imports in [`use`](https://doc.rust-lang.org/stable/std/keyword.use.html) and [`extern crate`](https://doc.rust-lang.org/stable/std/keyword.crate.html) statements: use std::{mem as memory, net as network}; // Now you can use the names `memory` and `network` to refer to `std::mem` and `std::net`. [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Ballow(unused_imports)%5D%0A++++use+std::%7Bmem+as+memory,+net+as+network%7D;%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.as.html#qualifying-paths) Qualifying paths ------------------------------------------------------------------------------------------- You’ll also find with `From` and `Into`, and indeed all traits, that `as` is used for the _fully qualified path_, a means of disambiguating associated items, i.e. functions, constants, and types. For example, if you have a type which implements two traits with identical method names (e.g. `Into::::into` and `Into::::into`), you can clarify which method you’ll use with `>::into(my_thing)`[1](https://doc.rust-lang.org/stable/std/keyword.as.html#fn1) . This is quite verbose, but fortunately, Rust’s type inference usually saves you from needing this, although it is occasionally necessary, especially with methods that return a generic type like `Into::into` or methods that don’t take `self`. It’s more common to use in macros where it can provide necessary hygiene. [§](https://doc.rust-lang.org/stable/std/keyword.as.html#further-reading) Further reading ----------------------------------------------------------------------------------------- For more information on what `as` is capable of, see the Reference on [type cast expressions](https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#type-cast-expressions) , [renaming imported entities](https://doc.rust-lang.org/reference/items/use-declarations.html#as-renames) , [renaming `extern` crates](https://doc.rust-lang.org/reference/items/extern-crates.html#r-items.extern-crate.as) and [qualified paths](https://doc.rust-lang.org/stable/reference/paths.html#qualified-paths) . * * * 1. You should probably never use this syntax with `Into` and instead write `T::from(my_thing)`. It just happens that there aren’t any great examples for this syntax in the standard library. Also, at time of writing, the compiler tends to suggest fully-qualified paths to fix ambiguous `Into::into` calls, so the example should hopefully be familiar. [↩](https://doc.rust-lang.org/stable/std/keyword.as.html#fnref1) --- # Redirecting... Redirecting to... [ch20-01-unsafe-rust.html](https://doc.rust-lang.org/stable/book/ch20-01-unsafe-rust.html) . --- # const - Rust [const](https://doc.rust-lang.org/stable/std/keyword.const.html#) ------------------------------------------------------------------ Keyword const Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#251) Expand description Compile-time constants, compile-time blocks, compile-time evaluable functions, and raw pointers. ### [§](https://doc.rust-lang.org/stable/std/keyword.const.html#compile-time-constants) Compile-time constants Sometimes a certain value is used many times throughout a program, and it can become inconvenient to copy it over and over. What’s more, it’s not always possible or desirable to make it a variable that gets carried around to each function that needs it. In these cases, the `const` keyword provides a convenient alternative to code duplication: const THING: u32 = 0xABAD1DEA; let foo = 123 + THING; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++const+THING:+u32+=+0xABAD1DEA;%0A++++%0A++++let+foo+=+123+%2B+THING;%0A%7D&edition=2024 "Run code") Constants must be explicitly typed; unlike with `let`, you can’t ignore their type and let the compiler figure it out. Any constant value can be defined in a `const`, which in practice happens to be most things that would be reasonable to have in a constant (barring `const fn`s). For example, you can’t have a [`File`](https://doc.rust-lang.org/stable/std/fs/struct.File.html "struct std::fs::File") as a `const`. The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses all others in a Rust program. For example, if you wanted to define a constant string, it would look like this: const WORDS: &'static str = "hello rust!"; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++const+WORDS:+%26%27static+str+=+%22hello+rust!%22;%0A%7D&edition=2024 "Run code") Thanks to static lifetime elision, you usually don’t have to explicitly use `'static`: const WORDS: &str = "hello convenience!"; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++const+WORDS:+%26str+=+%22hello+convenience!%22;%0A%7D&edition=2024 "Run code") `const` items look remarkably similar to `static` items, which introduces some confusion as to which one should be used at which times. To put it simply, constants are inlined wherever they’re used, making using them identical to simply replacing the name of the `const` with its value. Static variables, on the other hand, point to a single location in memory, which all accesses share. This means that, unlike with constants, they can’t have destructors, and act as a single value across the entire codebase. Constants, like statics, should always be in `SCREAMING_SNAKE_CASE`. For more detail on `const`, see the [Rust Book](https://doc.rust-lang.org/stable/book/ch03-01-variables-and-mutability.html#constants) or the [Reference](https://doc.rust-lang.org/stable/reference/items/constant-items.html) . ### [§](https://doc.rust-lang.org/stable/std/keyword.const.html#compile-time-blocks) Compile-time blocks The `const` keyword can also be used to define a block of code that is evaluated at compile time. This is useful for ensuring certain computations are completed before optimizations happen, as well as before runtime. For more details, see the [Reference](https://doc.rust-lang.org/stable/reference/expressions/block-expr.html#const-blocks) . ### [§](https://doc.rust-lang.org/stable/std/keyword.const.html#compile-time-evaluable-functions) Compile-time evaluable functions The other main use of the `const` keyword is in `const fn`. This marks a function as being callable in the body of a `const` or `static` item and in array initializers (commonly called “const contexts”). `const fn` are restricted in the set of operations they can perform, to ensure that they can be evaluated at compile-time. See the [Reference](https://doc.rust-lang.org/stable/reference/const_eval.html) for more detail. Turning a `fn` into a `const fn` has no effect on run-time uses of that function. ### [§](https://doc.rust-lang.org/stable/std/keyword.const.html#other-uses-of-const) Other uses of `const` The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const T` and `*mut T`. More about `const` as used in raw pointers can be read at the Rust docs for the [pointer primitive](https://doc.rust-lang.org/stable/std/primitive.pointer.html "primitive pointer") . --- # ref - Rust [ref](https://doc.rust-lang.org/stable/std/keyword.ref.html#) -------------------------------------------------------------- Keyword ref Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1210) Expand description Bind by reference during pattern matching. `ref` annotates pattern bindings to make them borrow rather than move. It is **not** a part of the pattern as far as matching is concerned: it does not affect _whether_ a value is matched, only _how_ it is matched. By default, [`match`](https://doc.rust-lang.org/stable/std/keyword.match.html) statements consume all they can, which can sometimes be a problem, when you don’t really need the value to be moved and owned: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.ref.html# "This example deliberately fails to compile") let maybe_name = Some(String::from("Alice")); // The variable 'maybe_name' is consumed here ... match maybe_name { Some(n) => println!("Hello, {n}"), _ => println!("Hello, world"), } // ... and is now unavailable. println!("Hello again, {}", maybe_name.unwrap_or("world".into())); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+maybe_name+=+Some(String::from(%22Alice%22));%0A++++//+The+variable+%27maybe_name%27+is+consumed+here+...%0A++++match+maybe_name+%7B%0A++++++++Some(n)+=%3E+println!(%22Hello,+%7Bn%7D%22),%0A++++++++_+=%3E+println!(%22Hello,+world%22),%0A++++%7D%0A++++//+...+and+is+now+unavailable.%0A++++println!(%22Hello+again,+%7B%7D%22,+maybe_name.unwrap_or(%22world%22.into()));%0A%7D&edition=2024 "Run code") Using the `ref` keyword, the value is only borrowed, not moved, making it available for use after the [`match`](https://doc.rust-lang.org/stable/std/keyword.match.html) statement: let maybe_name = Some(String::from("Alice")); // Using `ref`, the value is borrowed, not moved ... match maybe_name { Some(ref n) => println!("Hello, {n}"), _ => println!("Hello, world"), } // ... so it's available here! println!("Hello again, {}", maybe_name.unwrap_or("world".into())); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+maybe_name+=+Some(String::from(%22Alice%22));%0A++++//+Using+%60ref%60,+the+value+is+borrowed,+not+moved+...%0A++++match+maybe_name+%7B%0A++++++++Some(ref+n)+=%3E+println!(%22Hello,+%7Bn%7D%22),%0A++++++++_+=%3E+println!(%22Hello,+world%22),%0A++++%7D%0A++++//+...+so+it%27s+available+here!%0A++++println!(%22Hello+again,+%7B%7D%22,+maybe_name.unwrap_or(%22world%22.into()));%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.ref.html#-vs-ref) `&` vs `ref` ------------------------------------------------------------------------------- * `&` denotes that your pattern expects a reference to an object. Hence `&` is a part of said pattern: `&Foo` matches different objects than `Foo` does. * `ref` indicates that you want a reference to an unpacked value. It is not matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`. See also the [Reference](https://doc.rust-lang.org/stable/reference/patterns.html#identifier-patterns) for more information. --- # self - Rust [self](https://doc.rust-lang.org/stable/std/keyword.self.html#) ---------------------------------------------------------------- Keyword self Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1482) Expand description The receiver of a method, or the current module. `self` is used in two situations: referencing the current module and marking the receiver of a method. In paths, `self` can be used to refer to the current module, either in a [`use`](https://doc.rust-lang.org/stable/std/keyword.use.html) statement or in a path to access an element: use std::io::{self, Read}; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_imports)%5D%0A%0Afn+main()+%7B%0A++++use+std::io::%7Bself,+Read%7D;%0A%7D&edition=2024 "Run code") Is functionally the same as: use std::io; use std::io::Read; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_imports)%5D%0A%0Afn+main()+%7B%0A++++use+std::io;%0A++++use+std::io::Read;%0A%7D&edition=2024 "Run code") Using `self` to access an element in the current module: fn foo() {} fn bar() { self::foo() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%7D%0Afn+foo()+%7B%7D%0Afn+bar()+%7B%0A++++self::foo()%0A%7D&edition=2024 "Run code") `self` as the current receiver for a method allows to omit the parameter type most of the time. With the exception of this particularity, `self` is used much like any other parameter: struct Foo(i32); impl Foo { // No `self`. fn new() -> Self { Self(0) } // Consuming `self`. fn consume(self) -> Self { Self(self.0 + 1) } // Borrowing `self`. fn borrow(&self) -> &i32 { &self.0 } // Borrowing `self` mutably. fn borrow_mut(&mut self) -> &mut i32 { &mut self.0 } } // This method must be called with a `Type::` prefix. let foo = Foo::new(); assert_eq!(foo.0, 0); // Those two calls produces the same result. let foo = Foo::consume(foo); assert_eq!(foo.0, 1); let foo = foo.consume(); assert_eq!(foo.0, 2); // Borrowing is handled automatically with the second syntax. let borrow_1 = Foo::borrow(&foo); let borrow_2 = foo.borrow(); assert_eq!(borrow_1, borrow_2); // Borrowing mutably is handled automatically too with the second syntax. let mut foo = Foo::new(); *Foo::borrow_mut(&mut foo) += 1; assert_eq!(foo.0, 1); *foo.borrow_mut() += 1; assert_eq!(foo.0, 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Foo(i32);%0A++++%0A++++impl+Foo+%7B%0A++++++++//+No+%60self%60.%0A++++++++fn+new()+-%3E+Self+%7B%0A++++++++++++Self(0)%0A++++++++%7D%0A++++%0A++++++++//+Consuming+%60self%60.%0A++++++++fn+consume(self)+-%3E+Self+%7B%0A++++++++++++Self(self.0+%2B+1)%0A++++++++%7D%0A++++%0A++++++++//+Borrowing+%60self%60.%0A++++++++fn+borrow(%26self)+-%3E+%26i32+%7B%0A++++++++++++%26self.0%0A++++++++%7D%0A++++%0A++++++++//+Borrowing+%60self%60+mutably.%0A++++++++fn+borrow_mut(%26mut+self)+-%3E+%26mut+i32+%7B%0A++++++++++++%26mut+self.0%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+This+method+must+be+called+with+a+%60Type::%60+prefix.%0A++++let+foo+=+Foo::new();%0A++++assert_eq!(foo.0,+0);%0A++++%0A++++//+Those+two+calls+produces+the+same+result.%0A++++let+foo+=+Foo::consume(foo);%0A++++assert_eq!(foo.0,+1);%0A++++let+foo+=+foo.consume();%0A++++assert_eq!(foo.0,+2);%0A++++%0A++++//+Borrowing+is+handled+automatically+with+the+second+syntax.%0A++++let+borrow_1+=+Foo::borrow(%26foo);%0A++++let+borrow_2+=+foo.borrow();%0A++++assert_eq!(borrow_1,+borrow_2);%0A++++%0A++++//+Borrowing+mutably+is+handled+automatically+too+with+the+second+syntax.%0A++++let+mut+foo+=+Foo::new();%0A++++*Foo::borrow_mut(%26mut+foo)+%2B=+1;%0A++++assert_eq!(foo.0,+1);%0A++++*foo.borrow_mut()+%2B=+1;%0A++++assert_eq!(foo.0,+2);%0A%7D&edition=2024 "Run code") Note that this automatic conversion when calling `foo.method()` is not limited to the examples above. See the [Reference](https://doc.rust-lang.org/stable/reference/items/associated-items.html#methods) for more information. --- # super - Rust [super](https://doc.rust-lang.org/stable/std/keyword.super.html#) ------------------------------------------------------------------ Keyword super Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1773) Expand description The parent of the current [module](https://doc.rust-lang.org/stable/reference/items/modules.html) . mod a { pub fn foo() {} } mod b { pub fn foo() { super::a::foo(); // call a's foo function } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%7D%0Amod+a+%7B%0A++++pub+fn+foo()+%7B%7D%0A%7D%0Amod+b+%7B%0A++++pub+fn+foo()+%7B%0A++++++++super::a::foo();+//+call+a%27s+foo+function%0A++++%7D%0A%7D&edition=2024 "Run code") It is also possible to use `super` multiple times: `super::super::foo`, going up the ancestor chain. See the [Reference](https://doc.rust-lang.org/stable/reference/paths.html#super) for more information. --- # type - Rust [type](https://doc.rust-lang.org/stable/std/keyword.type.html#) ---------------------------------------------------------------- Keyword type Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2037) Expand description Define an [alias](https://doc.rust-lang.org/stable/reference/items/type-aliases.html) for an existing type. The syntax is `type Name = ExistingType;`. [§](https://doc.rust-lang.org/stable/std/keyword.type.html#examples) Examples ----------------------------------------------------------------------------- `type` does **not** create a new type: type Meters = u32; type Kilograms = u32; let m: Meters = 3; let k: Kilograms = 3; assert_eq!(m, k); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++type+Meters+=+u32;%0A++++type+Kilograms+=+u32;%0A++++%0A++++let+m:+Meters+=+3;%0A++++let+k:+Kilograms+=+3;%0A++++%0A++++assert_eq!(m,+k);%0A%7D&edition=2024 "Run code") A type can be generic: type ArcMutex = Arc>; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::%7BArc,+Mutex%7D;%0A++++type+ArcMutex%3CT%3E+=+Arc%3CMutex%3CT%3E%3E;%0A%7D&edition=2024 "Run code") In traits, `type` is used to declare an [associated type](https://doc.rust-lang.org/stable/reference/items/associated-items.html#associated-types) : trait Iterator { // associated type declaration type Item; fn next(&mut self) -> Option; } struct Once(Option); impl Iterator for Once { // associated type definition type Item = T; fn next(&mut self) -> Option { self.0.take() } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Iterator+%7B%0A++++++++//+associated+type+declaration%0A++++++++type+Item;%0A++++++++fn+next(%26mut+self)+-%3E+Option%3CSelf::Item%3E;%0A++++%7D%0A++++%0A++++struct+Once%3CT%3E(Option%3CT%3E);%0A++++%0A++++impl%3CT%3E+Iterator+for+Once%3CT%3E+%7B%0A++++++++//+associated+type+definition%0A++++++++type+Item+=+T;%0A++++++++fn+next(%26mut+self)+-%3E+Option%3CSelf::Item%3E+%7B%0A++++++++++++self.0.take()%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") --- # where - Rust [where](https://doc.rust-lang.org/stable/std/keyword.where.html#) ------------------------------------------------------------------ Keyword where Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2504) Expand description Add constraints that must be upheld to use an item. `where` allows specifying constraints on lifetime and generic parameters. The [RFC](https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md) introducing `where` contains detailed information about the keyword. [§](https://doc.rust-lang.org/stable/std/keyword.where.html#examples) Examples ------------------------------------------------------------------------------ `where` can be used for constraints with traits: fn new() -> T { T::default() } fn new_where() -> T where T: Default, { T::default() } assert_eq!(0.0, new()); assert_eq!(0.0, new_where()); assert_eq!(0, new()); assert_eq!(0, new_where()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+new%3CT:+Default%3E()+-%3E+T+%7B%0A++++++++T::default()%0A++++%7D%0A++++%0A++++fn+new_where%3CT%3E()+-%3E+T%0A++++where%0A++++++++T:+Default,%0A++++%7B%0A++++++++T::default()%0A++++%7D%0A++++%0A++++assert_eq!(0.0,+new());%0A++++assert_eq!(0.0,+new_where());%0A++++%0A++++assert_eq!(0,+new());%0A++++assert_eq!(0,+new_where());%0A%7D&edition=2024 "Run code") `where` can also be used for lifetimes. This compiles because `longer` outlives `shorter`, thus the constraint is respected: fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str where 'long: 'short, { if second { s2 } else { s1 } } let outer = String::from("Long living ref"); let longer = &outer; { let inner = String::from("Short living ref"); let shorter = &inner; assert_eq!(select(shorter, longer, false), shorter); assert_eq!(select(shorter, longer, true), longer); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+select%3C%27short,+%27long%3E(s1:+%26%27short+str,+s2:+%26%27long+str,+second:+bool)+-%3E+%26%27short+str%0A++++where%0A++++++++%27long:+%27short,%0A++++%7B%0A++++++++if+second+%7B+s2+%7D+else+%7B+s1+%7D%0A++++%7D%0A++++%0A++++let+outer+=+String::from(%22Long+living+ref%22);%0A++++let+longer+=+%26outer;%0A++++%7B%0A++++++++let+inner+=+String::from(%22Short+living+ref%22);%0A++++++++let+shorter+=+%26inner;%0A++++%0A++++++++assert_eq!(select(shorter,+longer,+false),+shorter);%0A++++++++assert_eq!(select(shorter,+longer,+true),+longer);%0A++++%7D%0A%7D&edition=2024 "Run code") On the other hand, this will not compile because the `where 'b: 'a` clause is missing: the `'b` lifetime is not known to live at least as long as `'a` which means this function cannot ensure it always returns a valid reference: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.where.html# "This example deliberately fails to compile") fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str { if second { s2 } else { s1 } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+select%3C%27a,+%27b%3E(s1:+%26%27a+str,+s2:+%26%27b+str,+second:+bool)+-%3E+%26%27a+str%0A++++%7B%0A++++++++if+second+%7B+s2+%7D+else+%7B+s1+%7D%0A++++%7D%0A%7D&edition=2024 "Run code") `where` can also be used to express more complicated constraints that cannot be written with the `` syntax: fn first_or_default(mut i: I) -> I::Item where I: Iterator, I::Item: Default, { i.next().unwrap_or_else(I::Item::default) } assert_eq!(first_or_default([1, 2, 3].into_iter()), 1); assert_eq!(first_or_default(Vec::::new().into_iter()), 0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+first_or_default%3CI%3E(mut+i:+I)+-%3E+I::Item%0A++++where%0A++++++++I:+Iterator,%0A++++++++I::Item:+Default,%0A++++%7B%0A++++++++i.next().unwrap_or_else(I::Item::default)%0A++++%7D%0A++++%0A++++assert_eq!(first_or_default(%5B1,+2,+3%5D.into_iter()),+1);%0A++++assert_eq!(first_or_default(Vec::%3Ci32%3E::new().into_iter()),+0);%0A%7D&edition=2024 "Run code") `where` is available anywhere generic and lifetime parameters are available, as can be seen with the [`Cow`](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") type from the standard library: pub enum Cow<'a, B> where B: ToOwned + ?Sized, { Borrowed(&'a B), Owned(::Owned), } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++pub+enum+Cow%3C%27a,+B%3E%0A++++where%0A++++++++B:+ToOwned+%2B+?Sized,%0A++++%7B%0A++++++++Borrowed(%26%27a+B),%0A++++++++Owned(%3CB+as+ToOwned%3E::Owned),%0A++++%7D%0A%7D&edition=2024 "Run code") --- # mut - Rust [mut](https://doc.rust-lang.org/stable/std/keyword.mut.html#) -------------------------------------------------------------- Keyword mut Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1145) Expand description A mutable variable, reference, or pointer. `mut` can be used in several situations. The first is mutable variables, which can be used anywhere you can bind a value to a variable name. Some examples: // A mutable variable in the parameter list of a function. fn foo(mut x: u8, y: u8) -> u8 { x += y; x } // Modifying a mutable variable. let mut a = 5; a = 6; assert_eq!(foo(3, 4), 7); assert_eq!(a, 6); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+A+mutable+variable+in+the+parameter+list+of+a+function.%0A++++fn+foo(mut+x:+u8,+y:+u8)+-%3E+u8+%7B%0A++++++++x+%2B=+y;%0A++++++++x%0A++++%7D%0A++++%0A++++//+Modifying+a+mutable+variable.%0A++++%23%5Ballow(unused_assignments)%5D%0A++++let+mut+a+=+5;%0A++++a+=+6;%0A++++%0A++++assert_eq!(foo(3,+4),+7);%0A++++assert_eq!(a,+6);%0A%7D&edition=2024 "Run code") The second is mutable references. They can be created from `mut` variables and must be unique: no other variables can have a mutable reference, nor a shared reference. // Taking a mutable reference. fn push_two(v: &mut Vec) { v.push(2); } // A mutable reference cannot be taken to a non-mutable variable. let mut v = vec![0, 1]; // Passing a mutable reference. push_two(&mut v); assert_eq!(v, vec![0, 1, 2]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+Taking+a+mutable+reference.%0A++++fn+push_two(v:+%26mut+Vec%3Cu8%3E)+%7B%0A++++++++v.push(2);%0A++++%7D%0A++++%0A++++//+A+mutable+reference+cannot+be+taken+to+a+non-mutable+variable.%0A++++let+mut+v+=+vec!%5B0,+1%5D;%0A++++//+Passing+a+mutable+reference.%0A++++push_two(%26mut+v);%0A++++%0A++++assert_eq!(v,+vec!%5B0,+1,+2%5D);%0A%7D&edition=2024 "Run code") [ⓘ](https://doc.rust-lang.org/stable/std/keyword.mut.html# "This example deliberately fails to compile") let mut v = vec![0, 1]; let mut_ref_v = &mut v; let ref_v = &v; mut_ref_v.push(2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+v+=+vec!%5B0,+1%5D;%0A++++let+mut_ref_v+=+%26mut+v;%0A++++%23%5Ballow(unused)%5D%0A++++let+ref_v+=+%26v;%0A++++mut_ref_v.push(2);%0A%7D&edition=2024 "Run code") Mutable raw pointers work much like mutable references, with the added possibility of not pointing to a valid object. The syntax is `*mut Type`. More information on mutable references and pointers can be found in the [Reference](https://doc.rust-lang.org/stable/reference/types/pointer.html#mutable-references-mut) . --- # println in std - Rust [println](https://doc.rust-lang.org/stable/std/macro.println.html#) -------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro println Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/macros.rs.html#138-145) macro_rules! println { () => { ... }; ($($arg:tt)*) => { ... }; } Expand description 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!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") , but writes to the standard output instead. See [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html "mod 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()`](https://doc.rust-lang.org/stable/std/io/struct.Stdout.html "struct std::io::Stdout") : use std::io::{stdout, Write}; let mut lock = stdout().lock(); writeln!(lock, "hello world").unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io::%7Bstdout,+Write%7D;%0A++++%0A++++let+mut+lock+=+stdout().lock();%0A++++writeln!(lock,+%22hello+world%22).unwrap();%0A%7D&edition=2024 "Run code") Use `println!` only for the primary output of your program. Use [`eprintln!`](https://doc.rust-lang.org/stable/std/macro.eprintln.html "macro std::eprintln") instead to print error and progress messages. See the formatting documentation in [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html "mod std::fmt") for details of the macro argument syntax. [§](https://doc.rust-lang.org/stable/std/macro.println.html#panics) Panics -------------------------------------------------------------------------- Panics if writing to [`io::stdout`](https://doc.rust-lang.org/stable/std/io/fn.stdout.html "fn std::io::stdout") fails. Writing to non-blocking stdout can cause an error, which will lead this macro to panic. [§](https://doc.rust-lang.org/stable/std/macro.println.html#examples) Examples ------------------------------------------------------------------------------ println!(); // prints just a newline println!("hello there!"); println!("format {} arguments", "some"); let local_variable = "some"; println!("format {local_variable} arguments"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++println!();+//+prints+just+a+newline%0A++++println!(%22hello+there!%22);%0A++++println!(%22format+%7B%7D+arguments%22,+%22some%22);%0A++++let+local_variable+=+%22some%22;%0A++++println!(%22format+%7Blocal_variable%7D+arguments%22);%0A%7D&edition=2024 "Run code") --- # return - Rust [return](https://doc.rust-lang.org/stable/std/keyword.return.html#) -------------------------------------------------------------------- Keyword return Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1287) Expand description Returns a value from a function. A `return` marks the end of an execution path in a function: fn foo() -> i32 { return 3; } assert_eq!(foo(), 3); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+foo()+-%3E+i32+%7B%0A++++++++return+3;%0A++++%7D%0A++++assert_eq!(foo(),+3);%0A%7D&edition=2024 "Run code") `return` is not needed when the returned value is the last expression in the function. In this case the `;` is omitted: fn foo() -> i32 { 3 } assert_eq!(foo(), 3); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+foo()+-%3E+i32+%7B%0A++++++++3%0A++++%7D%0A++++assert_eq!(foo(),+3);%0A%7D&edition=2024 "Run code") `return` returns from the function immediately (an “early return”): use std::fs::File; use std::io::{Error, ErrorKind, Read, Result}; fn main() -> Result<()> { let mut file = match File::open("foo.txt") { Ok(f) => f, Err(e) => return Err(e), }; let mut contents = String::new(); let size = match file.read_to_string(&mut contents) { Ok(s) => s, Err(e) => return Err(e), }; if contents.contains("impossible!") { return Err(Error::new(ErrorKind::Other, "oh no!")); } if size > 9000 { return Err(Error::new(ErrorKind::Other, "over 9000!")); } assert_eq!(contents, "Hello, world!"); Ok(()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::fs::File;%0Ause+std::io::%7BError,+ErrorKind,+Read,+Result%7D;%0A%0Afn+main()+-%3E+Result%3C()%3E+%7B%0A++++let+mut+file+=+match+File::open(%22foo.txt%22)+%7B%0A++++++++Ok(f)+=%3E+f,%0A++++++++Err(e)+=%3E+return+Err(e),%0A++++%7D;%0A%0A++++let+mut+contents+=+String::new();%0A++++let+size+=+match+file.read_to_string(%26mut+contents)+%7B%0A++++++++Ok(s)+=%3E+s,%0A++++++++Err(e)+=%3E+return+Err(e),%0A++++%7D;%0A%0A++++if+contents.contains(%22impossible!%22)+%7B%0A++++++++return+Err(Error::new(ErrorKind::Other,+%22oh+no!%22));%0A++++%7D%0A%0A++++if+size+%3E+9000+%7B%0A++++++++return+Err(Error::new(ErrorKind::Other,+%22over+9000!%22));%0A++++%7D%0A%0A++++assert_eq!(contents,+%22Hello,+world!%22);%0A++++Ok(())%0A%7D&edition=2024 "Run code") Within [closures](https://doc.rust-lang.org/stable/book/ch13-01-closures.html) and [`async`](https://doc.rust-lang.org/stable/std/keyword.async.html) blocks, `return` returns a value from within the closure or `async` block, not from the parent function: fn foo() -> i32 { let closure = || { return 5; }; let future = async { return 10; }; return 15; } assert_eq!(foo(), 15); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+foo()+-%3E+i32+%7B%0A++++++++let+closure+=+%7C%7C+%7B%0A++++++++++++return+5;%0A++++++++%7D;%0A++++%0A++++++++let+future+=+async+%7B%0A++++++++++++return+10;%0A++++++++%7D;%0A++++%0A++++++++return+15;%0A++++%7D%0A++++%0A++++assert_eq!(foo(),+15);%0A%7D&edition=2024 "Run code") --- # union - Rust [union](https://doc.rust-lang.org/stable/std/keyword.union.html#) ------------------------------------------------------------------ Keyword union Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2754) Expand description The [Rust equivalent of a C-style union](https://doc.rust-lang.org/stable/reference/items/unions.html) . A `union` looks like a [`struct`](https://doc.rust-lang.org/stable/std/keyword.struct.html) in terms of declaration, but all of its fields exist in the same memory, superimposed over one another. For instance, if we wanted some bits in memory that we sometimes interpret as a `u32` and sometimes as an `f32`, we could write: union IntOrFloat { i: u32, f: f32, } let mut u = IntOrFloat { f: 1.0 }; // Reading the fields of a union is always unsafe assert_eq!(unsafe { u.i }, 1065353216); // Updating through any of the field will modify all of them u.i = 1073741824; assert_eq!(unsafe { u.f }, 2.0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++union+IntOrFloat+%7B%0A++++++++i:+u32,%0A++++++++f:+f32,%0A++++%7D%0A++++%0A++++let+mut+u+=+IntOrFloat+%7B+f:+1.0+%7D;%0A++++//+Reading+the+fields+of+a+union+is+always+unsafe%0A++++assert_eq!(unsafe+%7B+u.i+%7D,+1065353216);%0A++++//+Updating+through+any+of+the+field+will+modify+all+of+them%0A++++u.i+=+1073741824;%0A++++assert_eq!(unsafe+%7B+u.f+%7D,+2.0);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.union.html#matching-on-unions) Matching on unions -------------------------------------------------------------------------------------------------- It is possible to use pattern matching on `union`s. A single field name must be used and it must match the name of one of the `union`’s field. Like reading from a `union`, pattern matching on a `union` requires `unsafe`. union IntOrFloat { i: u32, f: f32, } let u = IntOrFloat { f: 1.0 }; unsafe { match u { IntOrFloat { i: 10 } => println!("Found exactly ten!"), // Matching the field `f` provides an `f32`. IntOrFloat { f } => println!("Found f = {f} !"), } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++union+IntOrFloat+%7B%0A++++++++i:+u32,%0A++++++++f:+f32,%0A++++%7D%0A++++%0A++++let+u+=+IntOrFloat+%7B+f:+1.0+%7D;%0A++++%0A++++unsafe+%7B%0A++++++++match+u+%7B%0A++++++++++++IntOrFloat+%7B+i:+10+%7D+=%3E+println!(%22Found+exactly+ten!%22),%0A++++++++++++//+Matching+the+field+%60f%60+provides+an+%60f32%60.%0A++++++++++++IntOrFloat+%7B+f+%7D+=%3E+println!(%22Found+f+=+%7Bf%7D+!%22),%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.union.html#references-to-union-fields) References to union fields ------------------------------------------------------------------------------------------------------------------ All fields in a `union` are all at the same place in memory which means borrowing one borrows the entire `union`, for the same lifetime: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.union.html# "This example deliberately fails to compile") union IntOrFloat { i: u32, f: f32, } let mut u = IntOrFloat { f: 1.0 }; let f = unsafe { &u.f }; // This will not compile because the field has already been borrowed, even // if only immutably let i = unsafe { &mut u.i }; *i = 10; println!("f = {f} and i = {i}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++union+IntOrFloat+%7B%0A++++++++i:+u32,%0A++++++++f:+f32,%0A++++%7D%0A++++%0A++++let+mut+u+=+IntOrFloat+%7B+f:+1.0+%7D;%0A++++%0A++++let+f+=+unsafe+%7B+%26u.f+%7D;%0A++++//+This+will+not+compile+because+the+field+has+already+been+borrowed,+even%0A++++//+if+only+immutably%0A++++let+i+=+unsafe+%7B+%26mut+u.i+%7D;%0A++++%0A++++*i+=+10;%0A++++println!(%22f+=+%7Bf%7D+and+i+=+%7Bi%7D%22);%0A%7D&edition=2024 "Run code") See the [Reference](https://doc.rust-lang.org/stable/reference/items/unions.html) for more information on `union`s. --- # while - Rust [while](https://doc.rust-lang.org/stable/std/keyword.while.html#) ------------------------------------------------------------------ Keyword while Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2562) Expand description Loop while a condition is upheld. A `while` expression is used for predicate loops. The `while` expression runs the conditional expression before running the loop body, then runs the loop body if the conditional expression evaluates to `true`, or exits the loop otherwise. let mut counter = 0; while counter < 10 { println!("{counter}"); counter += 1; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+counter+=+0;%0A++++%0A++++while+counter+%3C+10+%7B%0A++++++++println!(%22%7Bcounter%7D%22);%0A++++++++counter+%2B=+1;%0A++++%7D%0A%7D&edition=2024 "Run code") Like the [`for`](https://doc.rust-lang.org/stable/std/keyword.for.html) expression, we can use `break` and `continue`. A `while` expression cannot break with a value and always evaluates to `()` unlike [`loop`](https://doc.rust-lang.org/stable/std/keyword.loop.html) . let mut i = 1; while i < 100 { i *= 2; if i == 64 { break; // Exit when `i` is 64. } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+i+=+1;%0A++++%0A++++while+i+%3C+100+%7B%0A++++++++i+*=+2;%0A++++++++if+i+==+64+%7B%0A++++++++++++break;+//+Exit+when+%60i%60+is+64.%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") As `if` expressions have their pattern matching variant in `if let`, so too do `while` expressions with `while let`. The `while let` expression matches the pattern against the expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise. We can use `break` and `continue` in `while let` expressions just like in `while`. let mut counter = Some(0); while let Some(i) = counter { if i == 10 { counter = None; } else { println!("{i}"); counter = Some (i + 1); } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+counter+=+Some(0);%0A++++%0A++++while+let+Some(i)+=+counter+%7B%0A++++++++if+i+==+10+%7B%0A++++++++++++counter+=+None;%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22%7Bi%7D%22);%0A++++++++++++counter+=+Some+(i+%2B+1);%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") For more information on `while` and loops in general, see the [reference](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html#predicate-loops) . See also, [`for`](https://doc.rust-lang.org/stable/std/keyword.for.html) , [`loop`](https://doc.rust-lang.org/stable/std/keyword.loop.html) . --- # Foreword - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") The Rust programming language has come a long way in a few short years, from its creation and incubation by a small and nascent community of enthusiasts, to becoming one of the most loved and in-demand programming languages in the world. Looking back, it was inevitable that the power and promise of Rust would turn heads and gain a foothold in systems programming. What was not inevitable was the global growth in interest and innovation that permeated through open source communities and catalyzed wide-scale adoption across industries. At this point in time, it is easy to point to the wonderful features that Rust has to offer to explain this explosion in interest and adoption. Who doesn’t want memory safety, _and_ fast performance, _and_ a friendly compiler, _and_ great tooling, among a host of other wonderful features? The Rust language you see today combines years of research in systems programming with the practical wisdom of a vibrant and passionate community. This language was designed with purpose and crafted with care, offering developers a tool that makes it easier to write safe, fast, and reliable code. But what makes Rust truly special is its roots in empowering you, the user, to achieve your goals. This is a language that wants you to succeed, and the principle of empowerment runs through the core of the community that builds, maintains, and advocates for this language. Since the previous edition of this definitive text, Rust has further developed into a truly global and trusted language. The Rust Project is now robustly supported by the Rust Foundation, which also invests in key initiatives to ensure that Rust is secure, stable, and sustainable. This edition of _The Rust Programming Language_ is a comprehensive update, reflecting the language’s evolution over the years and providing valuable new information. But it is not just a guide to syntax and libraries—it’s an invitation to join a community that values quality, performance, and thoughtful design. Whether you’re a seasoned developer looking to explore Rust for the first time or an experienced Rustacean looking to refine your skills, this edition offers something for everyone. The Rust journey has been one of collaboration, learning, and iteration. The growth of the language and its ecosystem is a direct reflection of the vibrant, diverse community behind it. The contributions of thousands of developers, from core language designers to casual contributors, are what make Rust such a unique and powerful tool. By picking up this book, you’re not just learning a new programming language—you’re joining a movement to make software better, safer, and more enjoyable to work with. Welcome to the Rust community! * Bec Rumbul, Executive Director of the Rust Foundation --- # pub - Rust [pub](https://doc.rust-lang.org/stable/std/keyword.pub.html#) -------------------------------------------------------------- Keyword pub Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1160) Expand description Make an item visible to others. The keyword `pub` makes any module, function, or data structure accessible from inside of external modules. The `pub` keyword may also be used in a `use` declaration to re-export an identifier from a namespace. For more information on the `pub` keyword, please see the visibility section of the [reference](https://doc.rust-lang.org/stable/reference/visibility-and-privacy.html?highlight=pub#visibility-and-privacy) and for some examples, see [Rust by Example](https://doc.rust-lang.org/stable/rust-by-example/mod/visibility.html) . --- # let - Rust [let](https://doc.rust-lang.org/stable/std/keyword.let.html#) -------------------------------------------------------------- Keyword let Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#902) Expand description Bind a value to a variable. The primary use for the `let` keyword is in `let` statements, which are used to introduce a new set of variables into the current scope, as given by a pattern. let thing1: i32 = 100; let thing2 = 200 + thing1; let mut changing_thing = true; changing_thing = false; let (part1, part2) = ("first", "second"); struct Example { a: bool, b: u64, } let Example { a, b: _ } = Example { a: true, b: 10004, }; assert!(a); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_assignments)%5D%0A%0Afn+main()+%7B%0A++++let+thing1:+i32+=+100;%0A++++let+thing2+=+200+%2B+thing1;%0A++++%0A++++let+mut+changing_thing+=+true;%0A++++changing_thing+=+false;%0A++++%0A++++let+(part1,+part2)+=+(%22first%22,+%22second%22);%0A++++%0A++++struct+Example+%7B%0A++++++++a:+bool,%0A++++++++b:+u64,%0A++++%7D%0A++++%0A++++let+Example+%7B+a,+b:+_+%7D+=+Example+%7B%0A++++++++a:+true,%0A++++++++b:+10004,%0A++++%7D;%0A++++assert!(a);%0A%7D&edition=2024 "Run code") The pattern is most commonly a single variable, which means no pattern matching is done and the expression given is bound to the variable. Apart from that, patterns used in `let` bindings can be as complicated as needed, given that the pattern is exhaustive. See the [Rust book](https://doc.rust-lang.org/stable/book/ch06-02-match.html) for more information on pattern matching. The type of the pattern is optionally given afterwards, but if left blank is automatically inferred by the compiler if possible. Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable. Multiple variables can be defined with the same name, known as shadowing. This doesn’t affect the original variable in any way beyond being unable to directly access it beyond the point of shadowing. It continues to remain in scope, getting dropped only when it falls out of scope. Shadowed variables don’t need to have the same type as the variables shadowing them. let shadowing_example = true; let shadowing_example = 123.4; let shadowing_example = shadowing_example as u32; let mut shadowing_example = format!("cool! {shadowing_example}"); shadowing_example += " something else!"; // not shadowing [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+shadowing_example+=+true;%0A++++let+shadowing_example+=+123.4;%0A++++let+shadowing_example+=+shadowing_example+as+u32;%0A++++let+mut+shadowing_example+=+format!(%22cool!+%7Bshadowing_example%7D%22);%0A++++shadowing_example+%2B=+%22+something+else!%22;%0A%7D&edition=2024 "Run code") Other places the `let` keyword is used include along with [`if`](https://doc.rust-lang.org/stable/std/keyword.if.html) , in the form of `if let` expressions. They’re useful if the pattern being matched isn’t exhaustive, such as with enumerations. `while let` also exists, which runs a loop with a pattern matched value until that pattern can’t be matched. For more information on the `let` keyword, see the [Rust book](https://doc.rust-lang.org/stable/book/ch18-01-all-the-places-for-patterns.html#let-statements) or the [Reference](https://doc.rust-lang.org/stable/reference/statements.html#let-statements) --- # Installation - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") The first step is to install Rust. We’ll download Rust through `rustup`, a command line tool for managing Rust versions and associated tools. You’ll need an internet connection for the download. Note: If you prefer not to use `rustup` for some reason, please see the [Other Rust Installation Methods page](https://forge.rust-lang.org/infra/other-installation-methods.html) for more options. The following steps install the latest stable version of the Rust compiler. Rust’s stability guarantees ensure that all the examples in the book that compile will continue to compile with newer Rust versions. The output might differ slightly between versions because Rust often improves error messages and warnings. In other words, any newer, stable version of Rust you install using these steps should work as expected with the content of this book. In this chapter and throughout the book, we’ll show some commands used in the terminal. Lines that you should enter in a terminal all start with `$`. You don’t need to type the `$` character; it’s the command line prompt shown to indicate the start of each command. Lines that don’t start with `$` typically show the output of the previous command. Additionally, PowerShell-specific examples will use `>` rather than `$`. If you’re using Linux or macOS, open a terminal and enter the following command: $ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh The command downloads a script and starts the installation of the `rustup` tool, which installs the latest stable version of Rust. You might be prompted for your password. If the install is successful, the following line will appear: Rust is installed now. Great! You will also need a _linker_, which is a program that Rust uses to join its compiled outputs into one file. It is likely you already have one. If you get linker errors, you should install a C compiler, which will typically include a linker. A C compiler is also useful because some common Rust packages depend on C code and will need a C compiler. On macOS, you can get a C compiler by running: $ xcode-select --install Linux users should generally install GCC or Clang, according to their distribution’s documentation. For example, if you use Ubuntu, you can install the `build-essential` package. On Windows, go to [https://www.rust-lang.org/tools/install](https://www.rust-lang.org/tools/install) and follow the instructions for installing Rust. At some point in the installation, you’ll be prompted to install Visual Studio. This provides a linker and the native libraries needed to compile programs. If you need more help with this step, see [https://rust-lang.github.io/rustup/installation/windows-msvc.html](https://rust-lang.github.io/rustup/installation/windows-msvc.html) . The rest of this book uses commands that work in both _cmd.exe_ and PowerShell. If there are specific differences, we’ll explain which to use. To check whether you have Rust installed correctly, open a shell and enter this line: $ rustc --version You should see the version number, commit hash, and commit date for the latest stable version that has been released, in the following format: rustc x.y.z (abcabcabc yyyy-mm-dd) If you see this information, you have installed Rust successfully! If you don’t see this information, check that Rust is in your `%PATH%` system variable as follows. In Windows CMD, use: > echo %PATH% In PowerShell, use: > echo $env:Path In Linux and macOS, use: $ echo $PATH If that’s all correct and Rust still isn’t working, there are a number of places you can get help. Find out how to get in touch with other Rustaceans (a silly nickname we call ourselves) on [the community page](https://www.rust-lang.org/community) . Once Rust is installed via `rustup`, updating to a newly released version is easy. From your shell, run the following update script: $ rustup update To uninstall Rust and `rustup`, run the following uninstall script from your shell: $ rustup self uninstall The installation of Rust also includes a local copy of the documentation so that you can read it offline. Run `rustup doc` to open the local documentation in your browser. Any time a type or function is provided by the standard library and you’re not sure what it does or how to use it, use the application programming interface (API) documentation to find out! This book makes no assumptions about what tools you use to author Rust code. Just about any text editor will get the job done! However, many text editors and integrated development environments (IDEs) have built-in support for Rust. You can always find a fairly current list of many editors and IDEs on [the tools page](https://www.rust-lang.org/tools) on the Rust website. In several examples, we will use Rust packages beyond the standard library. To work through those examples, you will either need to have an internet connection or to have downloaded those dependencies ahead of time. To download the dependencies ahead of time, you can run the following commands. (We’ll explain what `cargo` is and what each of these commands does in detail later.) $ cargo new get-dependencies $ cd get-dependencies $ cargo add rand@0.8.5 trpl@0.2.0 This will cache the downloads for these packages so you will not need to download them later. Once you have run this command, you do not need to keep the `get-dependencies` folder. If you have run this command, you can use the `--offline` flag with all `cargo` commands in the rest of the book to use these cached versions instead of attempting to use the network. --- # Introduction - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Note: This edition of the book is the same as [The Rust Programming Language](https://nostarch.com/rust-programming-language-3rd-edition) available in print and ebook format from [No Starch Press](https://nostarch.com/) . Welcome to _The Rust Programming Language_, an introductory book about Rust. The Rust programming language helps you write faster, more reliable software. High-level ergonomics and low-level control are often at odds in programming language design; Rust challenges that conflict. Through balancing powerful technical capacity and a great developer experience, Rust gives you the option to control low-level details (such as memory usage) without all the hassle traditionally associated with such control. Rust is ideal for many people for a variety of reasons. Let’s look at a few of the most important groups. Rust is proving to be a productive tool for collaborating among large teams of developers with varying levels of systems programming knowledge. Low-level code is prone to various subtle bugs, which in most other languages can only be caught through extensive testing and careful code review by experienced developers. In Rust, the compiler plays a gatekeeper role by refusing to compile code with these elusive bugs, including concurrency bugs. By working alongside the compiler, the team can spend its time focusing on the program’s logic rather than chasing down bugs. Rust also brings contemporary developer tools to the systems programming world: * Cargo, the included dependency manager and build tool, makes adding, compiling, and managing dependencies painless and consistent across the Rust ecosystem. * The `rustfmt` formatting tool ensures a consistent coding style across developers. * The Rust Language Server powers integrated development environment (IDE) integration for code completion and inline error messages. By using these and other tools in the Rust ecosystem, developers can be productive while writing systems-level code. Rust is for students and those who are interested in learning about systems concepts. Using Rust, many people have learned about topics like operating systems development. The community is very welcoming and happy to answer students’ questions. Through efforts such as this book, the Rust teams want to make systems concepts more accessible to more people, especially those new to programming. Hundreds of companies, large and small, use Rust in production for a variety of tasks, including command line tools, web services, DevOps tooling, embedded devices, audio and video analysis and transcoding, cryptocurrencies, bioinformatics, search engines, Internet of Things applications, machine learning, and even major parts of the Firefox web browser. Rust is for people who want to build the Rust programming language, community, developer tools, and libraries. We’d love to have you contribute to the Rust language. Rust is for people who crave speed and stability in a language. By speed, we mean both how quickly Rust code can run and the speed at which Rust lets you write programs. The Rust compiler’s checks ensure stability through feature additions and refactoring. This is in contrast to the brittle legacy code in languages without these checks, which developers are often afraid to modify. By striving for zero-cost abstractions—higher-level features that compile to lower-level code as fast as code written manually—Rust endeavors to make safe code be fast code as well. The Rust language hopes to support many other users as well; those mentioned here are merely some of the biggest stakeholders. Overall, Rust’s greatest ambition is to eliminate the trade-offs that programmers have accepted for decades by providing safety _and_ productivity, speed _and_ ergonomics. Give Rust a try, and see if its choices work for you. This book assumes that you’ve written code in another programming language, but it doesn’t make any assumptions about which one. We’ve tried to make the material broadly accessible to those from a wide variety of programming backgrounds. We don’t spend a lot of time talking about what programming _is_ or how to think about it. If you’re entirely new to programming, you would be better served by reading a book that specifically provides an introduction to programming. In general, this book assumes that you’re reading it in sequence from front to back. Later chapters build on concepts in earlier chapters, and earlier chapters might not delve into details on a particular topic but will revisit the topic in a later chapter. You’ll find two kinds of chapters in this book: concept chapters and project chapters. In concept chapters, you’ll learn about an aspect of Rust. In project chapters, we’ll build small programs together, applying what you’ve learned so far. Chapter 2, Chapter 12, and Chapter 21 are project chapters; the rest are concept chapters. **Chapter 1** explains how to install Rust, how to write a “Hello, world!” program, and how to use Cargo, Rust’s package manager and build tool. **Chapter 2** is a hands-on introduction to writing a program in Rust, having you build up a number-guessing game. Here, we cover concepts at a high level, and later chapters will provide additional detail. If you want to get your hands dirty right away, Chapter 2 is the place for that. If you’re a particularly meticulous learner who prefers to learn every detail before moving on to the next, you might want to skip Chapter 2 and go straight to **Chapter 3**, which covers Rust features that are similar to those of other programming languages; then, you can return to Chapter 2 when you’d like to work on a project applying the details you’ve learned. In **Chapter 4**, you’ll learn about Rust’s ownership system. **Chapter 5** discusses structs and methods. **Chapter 6** covers enums, `match` expressions, and the `if let` and `let...else` control flow constructs. You’ll use structs and enums to make custom types. In **Chapter 7**, you’ll learn about Rust’s module system and about privacy rules for organizing your code and its public application programming interface (API). **Chapter 8** discusses some common collection data structures that the standard library provides: vectors, strings, and hash maps. **Chapter 9** explores Rust’s error-handling philosophy and techniques. **Chapter 10** digs into generics, traits, and lifetimes, which give you the power to define code that applies to multiple types. **Chapter 11** is all about testing, which even with Rust’s safety guarantees is necessary to ensure that your program’s logic is correct. In **Chapter 12**, we’ll build our own implementation of a subset of functionality from the `grep` command line tool that searches for text within files. For this, we’ll use many of the concepts we discussed in the previous chapters. **Chapter 13** explores closures and iterators: features of Rust that come from functional programming languages. In **Chapter 14**, we’ll examine Cargo in more depth and talk about best practices for sharing your libraries with others. **Chapter 15** discusses smart pointers that the standard library provides and the traits that enable their functionality. In **Chapter 16**, we’ll walk through different models of concurrent programming and talk about how Rust helps you program in multiple threads fearlessly. In **Chapter 17**, we build on that by exploring Rust’s async and await syntax, along with tasks, futures, and streams, and the lightweight concurrency model they enable. **Chapter 18** looks at how Rust idioms compare to object-oriented programming principles you might be familiar with. **Chapter 19** is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. **Chapter 20** contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures. In **Chapter 21**, we’ll complete a project in which we’ll implement a low-level multithreaded web server! Finally, some appendixes contain useful information about the language in a more reference-like format. **Appendix A** covers Rust’s keywords, **Appendix B** covers Rust’s operators and symbols, **Appendix C** covers derivable traits provided by the standard library, **Appendix D** covers some useful development tools, and **Appendix E** explains Rust editions. In **Appendix F**, you can find translations of the book, and in **Appendix G** we’ll cover how Rust is made and what nightly Rust is. There is no wrong way to read this book: If you want to skip ahead, go for it! You might have to jump back to earlier chapters if you experience any confusion. But do whatever works for you. An important part of the process of learning Rust is learning how to read the error messages the compiler displays: These will guide you toward working code. As such, we’ll provide many examples that don’t compile along with the error message the compiler will show you in each situation. Know that if you enter and run a random example, it may not compile! Make sure you read the surrounding text to see whether the example you’re trying to run is meant to error. In most situations, we’ll lead you to the correct version of any code that doesn’t compile. Ferris will also help you distinguish code that isn’t meant to work: | Ferris | Meaning | | --- | --- | | ![Ferris with a question mark](https://doc.rust-lang.org/stable/book/img/ferris/does_not_compile.svg) | This code does not compile! | | ![Ferris throwing up their hands](https://doc.rust-lang.org/stable/book/img/ferris/panics.svg) | This code panics! | | ![Ferris with one claw up, shrugging](https://doc.rust-lang.org/stable/book/img/ferris/not_desired_behavior.svg) | This code does not produce the desired behavior. | In most situations, we’ll lead you to the correct version of any code that doesn’t compile. The source files from which this book is generated can be found on [GitHub](https://github.com/rust-lang/book/tree/main/src) . --- # true - Rust [true](https://doc.rust-lang.org/stable/std/keyword.true.html#) ---------------------------------------------------------------- Keyword true Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1985) Expand description A value of type [`bool`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") representing logical **true**. Logically `true` is not equal to [`false`](https://doc.rust-lang.org/stable/std/keyword.false.html) . ### [§](https://doc.rust-lang.org/stable/std/keyword.true.html#control-structures-that-check-for-true) Control structures that check for **true** Several of Rust’s control structures will check for a `bool` condition evaluating to **true**. * The condition in an [`if`](https://doc.rust-lang.org/stable/std/keyword.if.html) expression must be of type `bool`. Whenever that condition evaluates to **true**, the `if` expression takes on the value of the first block. If however, the condition evaluates to `false`, the expression takes on value of the `else` block if there is one. * [`while`](https://doc.rust-lang.org/stable/std/keyword.while.html) is another control flow construct expecting a `bool`\-typed condition. As long as the condition evaluates to **true**, the `while` loop will continually evaluate its associated block. * [`match`](https://doc.rust-lang.org/stable/reference/expressions/match-expr.html#match-guards) arms can have guard clauses on them. --- # mod - Rust [mod](https://doc.rust-lang.org/stable/std/keyword.mod.html#) -------------------------------------------------------------- Keyword mod Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1030) Expand description Organize code into [modules](https://doc.rust-lang.org/stable/reference/items/modules.html) . Use `mod` to create new [modules](https://doc.rust-lang.org/stable/reference/items/modules.html) to encapsulate code, including other modules: mod foo { mod bar { type MyType = (u8, u8); fn baz() {} } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++mod+foo+%7B%0A++++++++mod+bar+%7B%0A++++++++++++type+MyType+=+(u8,+u8);%0A++++++++++++fn+baz()+%7B%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Like [`struct`](https://doc.rust-lang.org/stable/std/keyword.struct.html) s and [`enum`](https://doc.rust-lang.org/stable/std/keyword.enum.html) s, a module and its content are private by default, inaccessible to code outside of the module. To learn more about allowing access, see the documentation for the [`pub`](https://doc.rust-lang.org/stable/std/keyword.pub.html) keyword. --- # move - Rust [move](https://doc.rust-lang.org/stable/std/keyword.move.html#) ---------------------------------------------------------------- Keyword move Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1087) Expand description Capture a [closure](https://doc.rust-lang.org/stable/book/ch13-01-closures.html) ’s environment by value. `move` converts any variables captured by reference or mutable reference to variables captured by value. let data = vec![1, 2, 3]; let closure = move || println!("captured {data:?} by value"); // data is no longer available, it is owned by the closure [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+data+=+vec!%5B1,+2,+3%5D;%0A++++let+closure+=+move+%7C%7C+println!(%22captured+%7Bdata:?%7D+by+value%22);%0A%7D&edition=2024 "Run code") Note: `move` closures may still implement [`Fn`](https://doc.rust-lang.org/stable/std/ops/trait.Fn.html "trait std::ops::Fn") or [`FnMut`](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") , even though they capture variables by `move`. This is because the traits implemented by a closure type are determined by _what_ the closure does with captured values, not _how_ it captures them: fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("This is a: {text}") } let fn_plain = create_fn(); fn_plain(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+create_fn()+-%3E+impl+Fn()+%7B%0A++++++++let+text+=+%22Fn%22.to_owned();%0A++++++++move+%7C%7C+println!(%22This+is+a:+%7Btext%7D%22)%0A++++%7D%0A++++%0A++++let+fn_plain+=+create_fn();%0A++++fn_plain();%0A%7D&edition=2024 "Run code") `move` is often used when [threads](https://doc.rust-lang.org/stable/book/ch16-01-threads.html#using-move-closures-with-threads) are involved. let data = vec![1, 2, 3]; std::thread::spawn(move || { println!("captured {data:?} by value") }).join().unwrap(); // data was moved to the spawned thread, so we cannot use it here [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+data+=+vec!%5B1,+2,+3%5D;%0A++++%0A++++std::thread::spawn(move+%7C%7C+%7B%0A++++++++println!(%22captured+%7Bdata:?%7D+by+value%22)%0A++++%7D).join().unwrap();%0A%7D&edition=2024 "Run code") `move` is also valid before an async block. let capture = "hello".to_owned(); let block = async move { println!("rust says {capture} from async block"); }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+capture+=+%22hello%22.to_owned();%0A++++let+block+=+async+move+%7B%0A++++++++println!(%22rust+says+%7Bcapture%7D+from+async+block%22);%0A++++%7D;%0A%7D&edition=2024 "Run code") For more information on the `move` keyword, see the [closures](https://doc.rust-lang.org/stable/book/ch13-01-closures.html) section of the Rust book or the [threads](https://doc.rust-lang.org/stable/book/ch16-01-threads.html#using-move-closures-with-threads) section. --- # use - Rust [use](https://doc.rust-lang.org/stable/std/keyword.use.html#) -------------------------------------------------------------- Keyword use Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2404) Expand description Import or rename items from other crates or modules, use values under ergonomic clones semantic, or specify precise capturing with `use<..>`. ### [§](https://doc.rust-lang.org/stable/std/keyword.use.html#importing-items) Importing items The `use` keyword is employed to shorten the path required to refer to a module item. The keyword may appear in modules, blocks, and even functions, typically at the top. The most basic usage of the keyword is `use path::to::item;`, though a number of convenient shortcuts are supported: * Simultaneously binding a list of paths with a common prefix, using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};` * Simultaneously binding a list of paths with a common prefix and their common parent module, using the [`self`](https://doc.rust-lang.org/stable/std/keyword.self.html) keyword, such as `use a::b::{self, c, d::e};` * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`. This can also be used with the last two features: `use a::b::{self as ab, c as abc}`. * Binding all paths matching a given prefix, using the asterisk wildcard syntax `use a::b::*;`. * Nesting groups of the previous features multiple times, such as `use a::b::{self as ab, c, d::{*, e::f}};` * Reexporting with visibility modifiers such as `pub use a::b;` * Importing with `_` to only import the methods of a trait without binding it to a name (to avoid conflict for example): `use ::std::io::Read as _;`. Using path qualifiers like [`crate`](https://doc.rust-lang.org/stable/std/keyword.crate.html) , [`super`](https://doc.rust-lang.org/stable/std/keyword.super.html) or [`self`](https://doc.rust-lang.org/stable/std/keyword.self.html) is supported: `use crate::a::b;`. Note that when the wildcard `*` is used on a type, it does not import its methods (though for `enum`s it imports the variants, as shown in the example below). [ⓘ](https://doc.rust-lang.org/stable/std/keyword.use.html# "This example deliberately fails to compile") enum ExampleEnum { VariantA, VariantB, } impl ExampleEnum { fn new() -> Self { Self::VariantA } } use ExampleEnum::*; // Compiles. let _ = VariantA; // Does not compile! let n = new(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+ExampleEnum+%7B%0A++++++++VariantA,%0A++++++++VariantB,%0A++++%7D%0A++++%0A++++impl+ExampleEnum+%7B%0A++++++++fn+new()+-%3E+Self+%7B%0A++++++++++++Self::VariantA%0A++++++++%7D%0A++++%7D%0A++++%0A++++use+ExampleEnum::*;%0A++++%0A++++//+Compiles.%0A++++let+_+=+VariantA;%0A++++%0A++++//+Does+not+compile!%0A++++let+n+=+new();%0A%7D&edition=2018 "Run code") For more information on `use` and paths in general, see the [Reference](https://doc.rust-lang.org/stable/reference/items/use-declarations.html) . The differences about paths and the `use` keyword between the 2015 and 2018 editions can also be found in the [Reference](https://doc.rust-lang.org/stable/reference/items/use-declarations.html) . ### [§](https://doc.rust-lang.org/stable/std/keyword.use.html#precise-capturing) Precise capturing The `use<..>` syntax is used within certain `impl Trait` bounds to control which generic parameters are captured. This is important for return-position `impl Trait` (RPIT) types, as it affects borrow checking by controlling which generic parameters can be used in the hidden type. For example, the following function demonstrates an error without precise capturing in Rust 2021 and earlier editions: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.use.html# "This example deliberately fails to compile") fn f(x: &()) -> impl Sized { x } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+f(x:+%26())+-%3E+impl+Sized+%7B+x+%7D%0A%7D&edition=2021 "Run code") By using `use<'_>` for precise capturing, it can be resolved: fn f(x: &()) -> impl Sized + use<'_> { x } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+f(x:+%26())+-%3E+impl+Sized+%2B+use%3C%27_%3E+%7B+x+%7D%0A%7D&edition=2024 "Run code") This syntax specifies that the elided lifetime be captured and therefore available for use in the hidden type. In Rust 2024, opaque types automatically capture all lifetime parameters in scope. `use<..>` syntax serves as an important way of opting-out of that default. For more details about precise capturing, see the [Reference](https://doc.rust-lang.org/stable/reference/types/impl-trait.html) . ### [§](https://doc.rust-lang.org/stable/std/keyword.use.html#ergonomic-clones) Ergonomic clones Use a values, copying its content if the value implements `Copy`, cloning the contents if the value implements `UseCloned` or moving it otherwise. --- # The Rust Programming Language - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") _by Steve Klabnik, Carol Nichols, and Chris Krycho, with contributions from the Rust Community_ This version of the text assumes you’re using Rust 1.85.0 (released 2025-02-17) or later with `edition = "2024"` in the _Cargo.toml_ file of all projects to configure them to use Rust 2024 Edition idioms. See the [“Installation” section of Chapter 1](https://doc.rust-lang.org/stable/book/ch01-01-installation.html) for instructions on installing or updating Rust, and see [Appendix E](https://doc.rust-lang.org/stable/book/appendix-05-editions.html) for information on editions. The HTML format is available online at [https://doc.rust-lang.org/stable/book/](https://doc.rust-lang.org/stable/book/) and offline with installations of Rust made with `rustup`; run `rustup doc --book` to open. Several community [translations](https://doc.rust-lang.org/stable/book/appendix-06-translation.html) are also available. This text is available in [paperback and ebook format from No Starch Press](https://nostarch.com/rust-programming-language-3rd-edition) . > **🚨 Want a more interactive learning experience? Try out a different version of the Rust Book, featuring: quizzes, highlighting, visualizations, and more**: [https://rust-book.cs.brown.edu](https://rust-book.cs.brown.edu/) --- # Common Programming Concepts - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") This chapter covers concepts that appear in almost every programming language and how they work in Rust. Many programming languages have much in common at their core. None of the concepts presented in this chapter are unique to Rust, but we’ll discuss them in the context of Rust and explain the conventions around using them. Specifically, you’ll learn about variables, basic types, functions, comments, and control flow. These foundations will be in every Rust program, and learning them early will give you a strong core to start from. The Rust language has a set of _keywords_ that are reserved for use by the language only, much as in other languages. Keep in mind that you cannot use these words as names of variables or functions. Most of the keywords have special meanings, and you’ll be using them to do various tasks in your Rust programs; a few have no current functionality associated with them but have been reserved for functionality that might be added to Rust in the future. You can find the list of the keywords in [Appendix A](https://doc.rust-lang.org/stable/book/appendix-01-keywords.html) . --- # Hello, World! - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Now that you’ve installed Rust, it’s time to write your first Rust program. It’s traditional when learning a new language to write a little program that prints the text `Hello, world!` to the screen, so we’ll do the same here! Note: This book assumes basic familiarity with the command line. Rust makes no specific demands about your editing or tooling or where your code lives, so if you prefer to use an IDE instead of the command line, feel free to use your favorite IDE. Many IDEs now have some degree of Rust support; check the IDE’s documentation for details. The Rust team has been focusing on enabling great IDE support via `rust-analyzer`. See [Appendix D](https://doc.rust-lang.org/stable/book/appendix-04-useful-development-tools.html) for more details. You’ll start by making a directory to store your Rust code. It doesn’t matter to Rust where your code lives, but for the exercises and projects in this book, we suggest making a _projects_ directory in your home directory and keeping all your projects there. Open a terminal and enter the following commands to make a _projects_ directory and a directory for the “Hello, world!” project within the _projects_ directory. For Linux, macOS, and PowerShell on Windows, enter this: $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world For Windows CMD, enter this: > mkdir "%USERPROFILE%\projects" > cd /d "%USERPROFILE%\projects" > mkdir hello_world > cd hello_world Next, make a new source file and call it _main.rs_. Rust files always end with the _.rs_ extension. If you’re using more than one word in your filename, the convention is to use an underscore to separate them. For example, use _hello\_world.rs_ rather than _helloworld.rs_. Now open the _main.rs_ file you just created and enter the code in Listing 1-1. Filename: main.rs fn main() { println!("Hello, world!"); } [Listing 1-1](https://doc.rust-lang.org/stable/book/ch01-02-hello-world.html#listing-1-1) : A program that prints `Hello, world!` Save the file and go back to your terminal window in the _~/projects/hello\_world_ directory. On Linux or macOS, enter the following commands to compile and run the file: $ rustc main.rs $ ./main Hello, world! On Windows, enter the command `.\main` instead of `./main`: > rustc main.rs > .\main Hello, world! Regardless of your operating system, the string `Hello, world!` should print to the terminal. If you don’t see this output, refer back to the [“Troubleshooting”](https://doc.rust-lang.org/stable/book/ch01-01-installation.html#troubleshooting) part of the Installation section for ways to get help. If `Hello, world!` did print, congratulations! You’ve officially written a Rust program. That makes you a Rust programmer—welcome! Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle: fn main() { } These lines define a function named `main`. The `main` function is special: It is always the first code that runs in every executable Rust program. Here, the first line declares a function named `main` that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses (`()`). The function body is wrapped in `{}`. Rust requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between. Note: If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called `rustfmt` to format your code in a particular style (more on `rustfmt` in [Appendix D](https://doc.rust-lang.org/stable/book/appendix-04-useful-development-tools.html) ). The Rust team has included this tool with the standard Rust distribution, as `rustc` is, so it should already be installed on your computer! The body of the `main` function holds the following code: #![allow(unused)] fn main() { println!("Hello, world!"); } This line does all the work in this little program: It prints text to the screen. There are three important details to notice here. First, `println!` calls a Rust macro. If it had called a function instead, it would be entered as `println` (without the `!`). Rust macros are a way to write code that generates code to extend Rust syntax, and we’ll discuss them in more detail in [Chapter 20](https://doc.rust-lang.org/stable/book/ch20-05-macros.html) . For now, you just need to know that using a `!` means that you’re calling a macro instead of a normal function and that macros don’t always follow the same rules as functions. Second, you see the `"Hello, world!"` string. We pass this string as an argument to `println!`, and the string is printed to the screen. Third, we end the line with a semicolon (`;`), which indicates that this expression is over, and the next one is ready to begin. Most lines of Rust code end with a semicolon. You’ve just run a newly created program, so let’s examine each step in the process. Before running a Rust program, you must compile it using the Rust compiler by entering the `rustc` command and passing it the name of your source file, like this: $ rustc main.rs If you have a C or C++ background, you’ll notice that this is similar to `gcc` or `clang`. After compiling successfully, Rust outputs a binary executable. On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the `ls` command in your shell: $ ls main main.rs On Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll see the same three files that you would see using CMD. With CMD on Windows, you would enter the following: > dir /B %= the /B option says to only show the file names =% main.exe main.pdb main.rs This shows the source code file with the _.rs_ extension, the executable file (_main.exe_ on Windows, but _main_ on all other platforms), and, when using Windows, a file containing debugging information with the _.pdb_ extension. From here, you run the _main_ or _main.exe_ file, like this: $ ./main # or .\main on Windows If your _main.rs_ is your “Hello, world!” program, this line prints `Hello, world!` to your terminal. If you’re more familiar with a dynamic language, such as Ruby, Python, or JavaScript, you might not be used to compiling and running a program as separate steps. Rust is an _ahead-of-time compiled_ language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed. If you give someone a _.rb_, _.py_, or _.js_ file, they need to have a Ruby, Python, or JavaScript implementation installed (respectively). But in those languages, you only need one command to compile and run your program. Everything is a trade-off in language design. Just compiling with `rustc` is fine for simple programs, but as your project grows, you’ll want to manage all the options and make it easy to share your code. Next, we’ll introduce you to the Cargo tool, which will help you write real-world Rust programs. --- # Hello, Cargo! - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Cargo is Rust’s build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries. (We call the libraries that your code needs _dependencies_.) The simplest Rust programs, like the one we’ve written so far, don’t have any dependencies. If we had built the “Hello, world!” project with Cargo, it would only use the part of Cargo that handles building your code. As you write more complex Rust programs, you’ll add dependencies, and if you start a project using Cargo, adding dependencies will be much easier to do. Because the vast majority of Rust projects use Cargo, the rest of this book assumes that you’re using Cargo too. Cargo comes installed with Rust if you used the official installers discussed in the [“Installation”](https://doc.rust-lang.org/stable/book/ch01-01-installation.html#installation) section. If you installed Rust through some other means, check whether Cargo is installed by entering the following in your terminal: $ cargo --version If you see a version number, you have it! If you see an error, such as `command not found`, look at the documentation for your method of installation to determine how to install Cargo separately. Let’s create a new project using Cargo and look at how it differs from our original “Hello, world!” project. Navigate back to your _projects_ directory (or wherever you decided to store your code). Then, on any operating system, run the following: $ cargo new hello_cargo $ cd hello_cargo The first command creates a new directory and project called _hello\_cargo_. We’ve named our project _hello\_cargo_, and Cargo creates its files in a directory of the same name. Go into the _hello\_cargo_ directory and list the files. You’ll see that Cargo has generated two files and one directory for us: a _Cargo.toml_ file and a _src_ directory with a _main.rs_ file inside. It has also initialized a new Git repository along with a _.gitignore_ file. Git files won’t be generated if you run `cargo new` within an existing Git repository; you can override this behavior by using `cargo new --vcs=git`. Note: Git is a common version control system. You can change `cargo new` to use a different version control system or no version control system by using the `--vcs` flag. Run `cargo new --help` to see the available options. Open _Cargo.toml_ in your text editor of choice. It should look similar to the code in Listing 1-2. Filename: Cargo.toml [package] name = "hello_cargo" version = "0.1.0" edition = "2024" [dependencies] [Listing 1-2](https://doc.rust-lang.org/stable/book/ch01-03-hello-cargo.html#listing-1-2) : Contents of _Cargo.toml_ generated by `cargo new` This file is in the [_TOML_](https://toml.io/) (_Tom’s Obvious, Minimal Language_) format, which is Cargo’s configuration format. The first line, `[package]`, is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections. The next three lines set the configuration information Cargo needs to compile your program: the name, the version, and the edition of Rust to use. We’ll talk about the `edition` key in [Appendix E](https://doc.rust-lang.org/stable/book/appendix-05-editions.html) . The last line, `[dependencies]`, is the start of a section for you to list any of your project’s dependencies. In Rust, packages of code are referred to as _crates_. We won’t need any other crates for this project, but we will in the first project in Chapter 2, so we’ll use this dependencies section then. Now open _src/main.rs_ and take a look: Filename: src/main.rs fn main() { println!("Hello, world!"); } Cargo has generated a “Hello, world!” program for you, just like the one we wrote in Listing 1-1! So far, the differences between our project and the project Cargo generated are that Cargo placed the code in the _src_ directory, and we have a _Cargo.toml_ configuration file in the top directory. Cargo expects your source files to live inside the _src_ directory. The top-level project directory is just for README files, license information, configuration files, and anything else not related to your code. Using Cargo helps you organize your projects. There’s a place for everything, and everything is in its place. If you started a project that doesn’t use Cargo, as we did with the “Hello, world!” project, you can convert it to a project that does use Cargo. Move the project code into the _src_ directory and create an appropriate _Cargo.toml_ file. One easy way to get that _Cargo.toml_ file is to run `cargo init`, which will create it for you automatically. Now let’s look at what’s different when we build and run the “Hello, world!” program with Cargo! From your _hello\_cargo_ directory, build your project by entering the following command: $ cargo build Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs This command creates an executable file in _target/debug/hello\_cargo_ (or _target\\debug\\hello\_cargo.exe_ on Windows) rather than in your current directory. Because the default build is a debug build, Cargo puts the binary in a directory named _debug_. You can run the executable with this command: $ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows Hello, world! If all goes well, `Hello, world!` should print to the terminal. Running `cargo build` for the first time also causes Cargo to create a new file at the top level: _Cargo.lock_. This file keeps track of the exact versions of dependencies in your project. This project doesn’t have dependencies, so the file is a bit sparse. You won’t ever need to change this file manually; Cargo manages its contents for you. We just built a project with `cargo build` and ran it with `./target/debug/hello_cargo`, but we can also use `cargo run` to compile the code and then run the resultant executable all in one command: $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/hello_cargo` Hello, world! Using `cargo run` is more convenient than having to remember to run `cargo build` and then use the whole path to the binary, so most developers use `cargo run`. Notice that this time we didn’t see output indicating that Cargo was compiling `hello_cargo`. Cargo figured out that the files hadn’t changed, so it didn’t rebuild but just ran the binary. If you had modified your source code, Cargo would have rebuilt the project before running it, and you would have seen this output: $ cargo run Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs Running `target/debug/hello_cargo` Hello, world! Cargo also provides a command called `cargo check`. This command quickly checks your code to make sure it compiles but doesn’t produce an executable: $ cargo check Checking hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs Why would you not want an executable? Often, `cargo check` is much faster than `cargo build` because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using `cargo check` will speed up the process of letting you know if your project is still compiling! As such, many Rustaceans run `cargo check` periodically as they write their program to make sure it compiles. Then, they run `cargo build` when they’re ready to use the executable. Let’s recap what we’ve learned so far about Cargo: * We can create a project using `cargo new`. * We can build a project using `cargo build`. * We can build and run a project in one step using `cargo run`. * We can build a project without producing a binary to check for errors using `cargo check`. * Instead of saving the result of the build in the same directory as our code, Cargo stores it in the _target/debug_ directory. An additional advantage of using Cargo is that the commands are the same no matter which operating system you’re working on. So, at this point, we’ll no longer provide specific instructions for Linux and macOS versus Windows. When your project is finally ready for release, you can use `cargo build --release` to compile it with optimizations. This command will create an executable in _target/release_ instead of _target/debug_. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible. If you’re benchmarking your code’s running time, be sure to run `cargo build --release` and benchmark with the executable in _target/release_. With simple projects, Cargo doesn’t provide a lot of value over just using `rustc`, but it will prove its worth as your programs become more intricate. Once programs grow to multiple files or need a dependency, it’s much easier to let Cargo coordinate the build. Even though the `hello_cargo` project is simple, it now uses much of the real tooling you’ll use in the rest of your Rust career. In fact, to work on any existing projects, you can use the following commands to check out the code using Git, change to that project’s directory, and build: $ git clone example.org/someproject $ cd someproject $ cargo build For more information about Cargo, check out [its documentation](https://doc.rust-lang.org/cargo/) . You’re already off to a great start on your Rust journey! In this chapter, you learned how to: * Install the latest stable version of Rust using `rustup`. * Update to a newer Rust version. * Open locally installed documentation. * Write and run a “Hello, world!” program using `rustc` directly. * Create and run a new project using the conventions of Cargo. This is a great time to build a more substantial program to get used to reading and writing Rust code. So, in Chapter 2, we’ll build a guessing game program. If you would rather start by learning how common programming concepts work in Rust, see Chapter 3 and then return to Chapter 2. --- # Closures - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they’re defined. We’ll demonstrate how these closure features allow for code reuse and behavior customization. We’ll first examine how we can use closures to capture values from the environment they’re defined in for later use. Here’s the scenario: Every so often, our T-shirt company gives away an exclusive, limited-edition shirt to someone on our mailing list as a promotion. People on the mailing list can optionally add their favorite color to their profile. If the person chosen for a free shirt has their favorite color set, they get that color shirt. If the person hasn’t specified a favorite color, they get whatever color the company currently has the most of. There are many ways to implement this. For this example, we’re going to use an enum called `ShirtColor` that has the variants `Red` and `Blue` (limiting the number of colors available for simplicity). We represent the company’s inventory with an `Inventory` struct that has a field named `shirts` that contains a `Vec` representing the shirt colors currently in stock. The method `giveaway` defined on `Inventory` gets the optional shirt color preference of the free-shirt winner, and it returns the shirt color the person will get. This setup is shown in Listing 13-1. Filename: src/main.rs #[derive(Debug, PartialEq, Copy, Clone)] enum ShirtColor { Red, Blue, } struct Inventory { shirts: Vec, } impl Inventory { fn giveaway(&self, user_preference: Option) -> ShirtColor { user_preference.unwrap_or_else(|| self.most_stocked()) } fn most_stocked(&self) -> ShirtColor { let mut num_red = 0; let mut num_blue = 0; for color in &self.shirts { match color { ShirtColor::Red => num_red += 1, ShirtColor::Blue => num_blue += 1, } } if num_red > num_blue { ShirtColor::Red } else { ShirtColor::Blue } } } fn main() { let store = Inventory { shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue], }; let user_pref1 = Some(ShirtColor::Red); let giveaway1 = store.giveaway(user_pref1); println!( "The user with preference {:?} gets {:?}", user_pref1, giveaway1 ); let user_pref2 = None; let giveaway2 = store.giveaway(user_pref2); println!( "The user with preference {:?} gets {:?}", user_pref2, giveaway2 ); } [Listing 13-1](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-1) : Shirt company giveaway situation The `store` defined in `main` has two blue shirts and one red shirt remaining to distribute for this limited-edition promotion. We call the `giveaway` method for a user with a preference for a red shirt and a user without any preference. Again, this code could be implemented in many ways, and here, to focus on closures, we’ve stuck to concepts you’ve already learned, except for the body of the `giveaway` method that uses a closure. In the `giveaway` method, we get the user preference as a parameter of type `Option` and call the `unwrap_or_else` method on `user_preference`. The [`unwrap_or_else` method on `Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_or_else) is defined by the standard library. It takes one argument: a closure without any arguments that returns a value `T` (the same type stored in the `Some` variant of the `Option`, in this case `ShirtColor`). If the `Option` is the `Some` variant, `unwrap_or_else` returns the value from within the `Some`. If the `Option` is the `None` variant, `unwrap_or_else` calls the closure and returns the value returned by the closure. We specify the closure expression `|| self.most_stocked()` as the argument to `unwrap_or_else`. This is a closure that takes no parameters itself (if the closure had parameters, they would appear between the two vertical pipes). The body of the closure calls `self.most_stocked()`. We’re defining the closure here, and the implementation of `unwrap_or_else` will evaluate the closure later if the result is needed. Running this code prints the following: $ cargo run Compiling shirt-company v0.1.0 (file:///projects/shirt-company) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s Running `target/debug/shirt-company` The user with preference Some(Red) gets Red The user with preference None gets Blue One interesting aspect here is that we’ve passed a closure that calls `self.most_stocked()` on the current `Inventory` instance. The standard library didn’t need to know anything about the `Inventory` or `ShirtColor` types we defined, or the logic we want to use in this scenario. The closure captures an immutable reference to the `self` `Inventory` instance and passes it with the code we specify to the `unwrap_or_else` method. Functions, on the other hand, are not able to capture their environment in this way. There are more differences between functions and closures. Closures don’t usually require you to annotate the types of the parameters or the return value like `fn` functions do. Type annotations are required on functions because the types are part of an explicit interface exposed to your users. Defining this interface rigidly is important for ensuring that everyone agrees on what types of values a function uses and returns. Closures, on the other hand, aren’t used in an exposed interface like this: They’re stored in variables, and they’re used without naming them and exposing them to users of our library. Closures are typically short and relevant only within a narrow context rather than in any arbitrary scenario. Within these limited contexts, the compiler can infer the types of the parameters and the return type, similar to how it’s able to infer the types of most variables (there are rare cases where the compiler needs closure type annotations too). As with variables, we can add type annotations if we want to increase explicitness and clarity at the cost of being more verbose than is strictly necessary. Annotating the types for a closure would look like the definition shown in Listing 13-2. In this example, we’re defining a closure and storing it in a variable rather than defining the closure in the spot we pass it as an argument, as we did in Listing 13-1. Filename: src/main.rs use std::thread; use std::time::Duration; fn generate_workout(intensity: u32, random_number: u32) { let expensive_closure = |num: u32| -> u32 { println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); num }; if intensity < 25 { println!("Today, do {} pushups!", expensive_closure(intensity)); println!("Next, do {} situps!", expensive_closure(intensity)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_closure(intensity) ); } } } fn main() { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout(simulated_user_specified_value, simulated_random_number); } [Listing 13-2](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-2) : Adding optional type annotations of the parameter and return value types in the closure With type annotations added, the syntax of closures looks more similar to the syntax of functions. Here, we define a function that adds 1 to its parameter and a closure that has the same behavior, for comparison. We’ve added some spaces to line up the relevant parts. This illustrates how closure syntax is similar to function syntax except for the use of pipes and the amount of syntax that is optional: fn add_one_v1 (x: u32) -> u32 { x + 1 } let add_one_v2 = |x: u32| -> u32 { x + 1 }; let add_one_v3 = |x| { x + 1 }; let add_one_v4 = |x| x + 1 ; The first line shows a function definition and the second line shows a fully annotated closure definition. In the third line, we remove the type annotations from the closure definition. In the fourth line, we remove the brackets, which are optional because the closure body has only one expression. These are all valid definitions that will produce the same behavior when they’re called. The `add_one_v3` and `add_one_v4` lines require the closures to be evaluated to be able to compile because the types will be inferred from their usage. This is similar to `let v = Vec::new();` needing either type annotations or values of some type to be inserted into the `Vec` for Rust to be able to infer the type. For closure definitions, the compiler will infer one concrete type for each of their parameters and for their return value. For instance, Listing 13-3 shows the definition of a short closure that just returns the value it receives as a parameter. This closure isn’t very useful except for the purposes of this example. Note that we haven’t added any type annotations to the definition. Because there are no type annotations, we can call the closure with any type, which we’ve done here with `String` the first time. If we then try to call `example_closure` with an integer, we’ll get an error. Filename: src/main.rs fn main() { let example_closure = |x| x; let s = example_closure(String::from("hello")); let n = example_closure(5); } [Listing 13-3](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-3) : Attempting to call a closure whose types are inferred with two different types The compiler gives us this error: $ cargo run Compiling closure-example v0.1.0 (file:///projects/closure-example) error[E0308]: mismatched types --> src/main.rs:5:29 | 5 | let n = example_closure(5); | --------------- ^- help: try using a conversion method: `.to_string()` | | | | | expected `String`, found integer | arguments to this function are incorrect | note: expected because the closure was earlier called with an argument of type `String` --> src/main.rs:4:29 | 4 | let s = example_closure(String::from("hello")); | --------------- ^^^^^^^^^^^^^^^^^^^^^ expected because this argument is of type `String` | | | in this closure call note: closure parameter defined here --> src/main.rs:2:28 | 2 | let example_closure = |x| x; | ^ For more information about this error, try `rustc --explain E0308`. error: could not compile `closure-example` (bin "closure-example") due to 1 previous error The first time we call `example_closure` with the `String` value, the compiler infers the type of `x` and the return type of the closure to be `String`. Those types are then locked into the closure in `example_closure`, and we get a type error when we next try to use a different type with the same closure. Closures can capture values from their environment in three ways, which directly map to the three ways a function can take a parameter: borrowing immutably, borrowing mutably, and taking ownership. The closure will decide which of these to use based on what the body of the function does with the captured values. In Listing 13-4, we define a closure that captures an immutable reference to the vector named `list` because it only needs an immutable reference to print the value. Filename: src/main.rs fn main() { let list = vec![1, 2, 3]; println!("Before defining closure: {list:?}"); let only_borrows = || println!("From closure: {list:?}"); println!("Before calling closure: {list:?}"); only_borrows(); println!("After calling closure: {list:?}"); } [Listing 13-4](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-4) : Defining and calling a closure that captures an immutable reference This example also illustrates that a variable can bind to a closure definition, and we can later call the closure by using the variable name and parentheses as if the variable name were a function name. Because we can have multiple immutable references to `list` at the same time, `list` is still accessible from the code before the closure definition, after the closure definition but before the closure is called, and after the closure is called. This code compiles, runs, and prints: $ cargo run Compiling closure-example v0.1.0 (file:///projects/closure-example) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/closure-example` Before defining closure: [1, 2, 3] Before calling closure: [1, 2, 3] From closure: [1, 2, 3] After calling closure: [1, 2, 3] Next, in Listing 13-5, we change the closure body so that it adds an element to the `list` vector. The closure now captures a mutable reference. Filename: src/main.rs fn main() { let mut list = vec![1, 2, 3]; println!("Before defining closure: {list:?}"); let mut borrows_mutably = || list.push(7); borrows_mutably(); println!("After calling closure: {list:?}"); } [Listing 13-5](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-5) : Defining and calling a closure that captures a mutable reference This code compiles, runs, and prints: $ cargo run Compiling closure-example v0.1.0 (file:///projects/closure-example) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/closure-example` Before defining closure: [1, 2, 3] After calling closure: [1, 2, 3, 7] Note that there’s no longer a `println!` between the definition and the call of the `borrows_mutably` closure: When `borrows_mutably` is defined, it captures a mutable reference to `list`. We don’t use the closure again after the closure is called, so the mutable borrow ends. Between the closure definition and the closure call, an immutable borrow to print isn’t allowed, because no other borrows are allowed when there’s a mutable borrow. Try adding a `println!` there to see what error message you get! If you want to force the closure to take ownership of the values it uses in the environment even though the body of the closure doesn’t strictly need ownership, you can use the `move` keyword before the parameter list. This technique is mostly useful when passing a closure to a new thread to move the data so that it’s owned by the new thread. We’ll discuss threads and why you would want to use them in detail in Chapter 16 when we talk about concurrency, but for now, let’s briefly explore spawning a new thread using a closure that needs the `move` keyword. Listing 13-6 shows Listing 13-4 modified to print the vector in a new thread rather than in the main thread. Filename: src/main.rs use std::thread; fn main() { let list = vec![1, 2, 3]; println!("Before defining closure: {list:?}"); thread::spawn(move || println!("From thread: {list:?}")) .join() .unwrap(); } [Listing 13-6](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-6) : Using `move` to force the closure for the thread to take ownership of `list` We spawn a new thread, giving the thread a closure to run as an argument. The closure body prints out the list. In Listing 13-4, the closure only captured `list` using an immutable reference because that’s the least amount of access to `list` needed to print it. In this example, even though the closure body still only needs an immutable reference, we need to specify that `list` should be moved into the closure by putting the `move` keyword at the beginning of the closure definition. If the main thread performed more operations before calling `join` on the new thread, the new thread might finish before the rest of the main thread finishes, or the main thread might finish first. If the main thread maintained ownership of `list` but ended before the new thread and drops `list`, the immutable reference in the thread would be invalid. Therefore, the compiler requires that `list` be moved into the closure given to the new thread so that the reference will be valid. Try removing the `move` keyword or using `list` in the main thread after the closure is defined to see what compiler errors you get! Once a closure has captured a reference or captured ownership of a value from the environment where the closure is defined (thus affecting what, if anything, is moved _into_ the closure), the code in the body of the closure defines what happens to the references or values when the closure is evaluated later (thus affecting what, if anything, is moved _out of_ the closure). A closure body can do any of the following: Move a captured value out of the closure, mutate the captured value, neither move nor mutate the value, or capture nothing from the environment to begin with. The way a closure captures and handles values from the environment affects which traits the closure implements, and traits are how functions and structs can specify what kinds of closures they can use. Closures will automatically implement one, two, or all three of these `Fn` traits, in an additive fashion, depending on how the closure’s body handles the values: * `FnOnce` applies to closures that can be called once. All closures implement at least this trait because all closures can be called. A closure that moves captured values out of its body will only implement `FnOnce` and none of the other `Fn` traits because it can only be called once. * `FnMut` applies to closures that don’t move captured values out of their body but might mutate the captured values. These closures can be called more than once. * `Fn` applies to closures that don’t move captured values out of their body and don’t mutate captured values, as well as closures that capture nothing from their environment. These closures can be called more than once without mutating their environment, which is important in cases such as calling a closure multiple times concurrently. Let’s look at the definition of the `unwrap_or_else` method on `Option` that we used in Listing 13-1: impl Option { pub fn unwrap_or_else(self, f: F) -> T where F: FnOnce() -> T { match self { Some(x) => x, None => f(), } } } Recall that `T` is the generic type representing the type of the value in the `Some` variant of an `Option`. That type `T` is also the return type of the `unwrap_or_else` function: Code that calls `unwrap_or_else` on an `Option`, for example, will get a `String`. Next, notice that the `unwrap_or_else` function has the additional generic type parameter `F`. The `F` type is the type of the parameter named `f`, which is the closure we provide when calling `unwrap_or_else`. The trait bound specified on the generic type `F` is `FnOnce() -> T`, which means `F` must be able to be called once, take no arguments, and return a `T`. Using `FnOnce` in the trait bound expresses the constraint that `unwrap_or_else` will not call `f` more than once. In the body of `unwrap_or_else`, we can see that if the `Option` is `Some`, `f` won’t be called. If the `Option` is `None`, `f` will be called once. Because all closures implement `FnOnce`, `unwrap_or_else` accepts all three kinds of closures and is as flexible as it can be. Note: If what we want to do doesn’t require capturing a value from the environment, we can use the name of a function rather than a closure where we need something that implements one of the `Fn` traits. For example, on an `Option>` value, we could call `unwrap_or_else(Vec::new)` to get a new, empty vector if the value is `None`. The compiler automatically implements whichever of the `Fn` traits is applicable for a function definition. Now let’s look at the standard library method `sort_by_key`, defined on slices, to see how that differs from `unwrap_or_else` and why `sort_by_key` uses `FnMut` instead of `FnOnce` for the trait bound. The closure gets one argument in the form of a reference to the current item in the slice being considered, and it returns a value of type `K` that can be ordered. This function is useful when you want to sort a slice by a particular attribute of each item. In Listing 13-7, we have a list of `Rectangle` instances, and we use `sort_by_key` to order them by their `width` attribute from low to high. Filename: src/main.rs #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [\ Rectangle { width: 10, height: 1 },\ Rectangle { width: 3, height: 5 },\ Rectangle { width: 7, height: 12 },\ ]; list.sort_by_key(|r| r.width); println!("{list:#?}"); } [Listing 13-7](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-7) : Using `sort_by_key` to order rectangles by width This code prints: $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.41s Running `target/debug/rectangles` [\ Rectangle {\ width: 3,\ height: 5,\ },\ Rectangle {\ width: 7,\ height: 12,\ },\ Rectangle {\ width: 10,\ height: 1,\ },\ ] The reason `sort_by_key` is defined to take an `FnMut` closure is that it calls the closure multiple times: once for each item in the slice. The closure `|r| r.width` doesn’t capture, mutate, or move anything out from its environment, so it meets the trait bound requirements. In contrast, Listing 13-8 shows an example of a closure that implements just the `FnOnce` trait, because it moves a value out of the environment. The compiler won’t let us use this closure with `sort_by_key`. Filename: src/main.rs #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [\ Rectangle { width: 10, height: 1 },\ Rectangle { width: 3, height: 5 },\ Rectangle { width: 7, height: 12 },\ ]; let mut sort_operations = vec![]; let value = String::from("closure called"); list.sort_by_key(|r| { sort_operations.push(value); r.width }); println!("{list:#?}"); } [Listing 13-8](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-8) : Attempting to use an `FnOnce` closure with `sort_by_key` This is a contrived, convoluted way (that doesn’t work) to try to count the number of times `sort_by_key` calls the closure when sorting `list`. This code attempts to do this counting by pushing `value`—a `String` from the closure’s environment—into the `sort_operations` vector. The closure captures `value` and then moves `value` out of the closure by transferring ownership of `value` to the `sort_operations` vector. This closure can be called once; trying to call it a second time wouldn’t work, because `value` would no longer be in the environment to be pushed into `sort_operations` again! Therefore, this closure only implements `FnOnce`. When we try to compile this code, we get this error that `value` can’t be moved out of the closure because the closure must implement `FnMut`: $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure --> src/main.rs:18:30 | 15 | let value = String::from("closure called"); | ----- captured outer variable 16 | 17 | list.sort_by_key(|r| { | --- captured by this `FnMut` closure 18 | sort_operations.push(value); | ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait | help: consider cloning the value if the performance cost is acceptable | 18 | sort_operations.push(value.clone()); | ++++++++ For more information about this error, try `rustc --explain E0507`. error: could not compile `rectangles` (bin "rectangles") due to 1 previous error The error points to the line in the closure body that moves `value` out of the environment. To fix this, we need to change the closure body so that it doesn’t move values out of the environment. Keeping a counter in the environment and incrementing its value in the closure body is a more straightforward way to count the number of times the closure is called. The closure in Listing 13-9 works with `sort_by_key` because it is only capturing a mutable reference to the `num_sort_operations` counter and can therefore be called more than once. Filename: src/main.rs #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [\ Rectangle { width: 10, height: 1 },\ Rectangle { width: 3, height: 5 },\ Rectangle { width: 7, height: 12 },\ ]; let mut num_sort_operations = 0; list.sort_by_key(|r| { num_sort_operations += 1; r.width }); println!("{list:#?}, sorted in {num_sort_operations} operations"); } [Listing 13-9](https://doc.rust-lang.org/stable/book/ch13-01-closures.html#listing-13-9) : Using an `FnMut` closure with `sort_by_key` is allowed. The `Fn` traits are important when defining or using functions or types that make use of closures. In the next section, we’ll discuss iterators. Many iterator methods take closure arguments, so keep these closure details in mind as we continue! --- # Variables and Mutability - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") As mentioned in the [“Storing Values with Variables”](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#storing-values-with-variables) section, by default, variables are immutable. This is one of many nudges Rust gives you to write your code in a way that takes advantage of the safety and easy concurrency that Rust offers. However, you still have the option to make your variables mutable. Let’s explore how and why Rust encourages you to favor immutability and why sometimes you might want to opt out. When a variable is immutable, once a value is bound to a name, you can’t change that value. To illustrate this, generate a new project called _variables_ in your _projects_ directory by using `cargo new variables`. Then, in your new _variables_ directory, open _src/main.rs_ and replace its code with the following code, which won’t compile just yet: Filename: src/main.rs fn main() { let x = 5; println!("The value of x is: {x}"); x = 6; println!("The value of x is: {x}"); } Save and run the program using `cargo run`. You should receive an error message regarding an immutability error, as shown in this output: $ cargo run Compiling variables v0.1.0 (file:///projects/variables) error[E0384]: cannot assign twice to immutable variable `x` --> src/main.rs:4:5 | 2 | let x = 5; | - first assignment to `x` 3 | println!("The value of x is: {x}"); 4 | x = 6; | ^^^^^ cannot assign twice to immutable variable | help: consider making this binding mutable | 2 | let mut x = 5; | +++ For more information about this error, try `rustc --explain E0384`. error: could not compile `variables` (bin "variables") due to 1 previous error This example shows how the compiler helps you find errors in your programs. Compiler errors can be frustrating, but really they only mean your program isn’t safely doing what you want it to do yet; they do _not_ mean that you’re not a good programmer! Experienced Rustaceans still get compiler errors. You received the error message `` cannot assign twice to immutable variable `x` `` because you tried to assign a second value to the immutable `x` variable. It’s important that we get compile-time errors when we attempt to change a value that’s designated as immutable, because this very situation can lead to bugs. If one part of our code operates on the assumption that a value will never change and another part of our code changes that value, it’s possible that the first part of the code won’t do what it was designed to do. The cause of this kind of bug can be difficult to track down after the fact, especially when the second piece of code changes the value only _sometimes_. The Rust compiler guarantees that when you state that a value won’t change, it really won’t change, so you don’t have to keep track of it yourself. Your code is thus easier to reason through. But mutability can be very useful and can make code more convenient to write. Although variables are immutable by default, you can make them mutable by adding `mut` in front of the variable name as you did in [Chapter 2](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#storing-values-with-variables) . Adding `mut` also conveys intent to future readers of the code by indicating that other parts of the code will be changing this variable’s value. For example, let’s change _src/main.rs_ to the following: Filename: src/main.rs fn main() { let mut x = 5; println!("The value of x is: {x}"); x = 6; println!("The value of x is: {x}"); } When we run the program now, we get this: $ cargo run Compiling variables v0.1.0 (file:///projects/variables) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s Running `target/debug/variables` The value of x is: 5 The value of x is: 6 We’re allowed to change the value bound to `x` from `5` to `6` when `mut` is used. Ultimately, deciding whether to use mutability or not is up to you and depends on what you think is clearest in that particular situation. Like immutable variables, _constants_ are values that are bound to a name and are not allowed to change, but there are a few differences between constants and variables. First, you aren’t allowed to use `mut` with constants. Constants aren’t just immutable by default—they’re always immutable. You declare constants using the `const` keyword instead of the `let` keyword, and the type of the value _must_ be annotated. We’ll cover types and type annotations in the next section, [“Data Types”](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html#data-types) , so don’t worry about the details right now. Just know that you must always annotate the type. Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of code need to know about. The last difference is that constants may be set only to a constant expression, not the result of a value that could only be computed at runtime. Here’s an example of a constant declaration: #![allow(unused)] fn main() { const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; } The constant’s name is `THREE_HOURS_IN_SECONDS`, and its value is set to the result of multiplying 60 (the number of seconds in a minute) by 60 (the number of minutes in an hour) by 3 (the number of hours we want to count in this program). Rust’s naming convention for constants is to use all uppercase with underscores between words. The compiler is able to evaluate a limited set of operations at compile time, which lets us choose to write out this value in a way that’s easier to understand and verify, rather than setting this constant to the value 10,800. See the [Rust Reference’s section on constant evaluation](https://doc.rust-lang.org/stable/reference/const_eval.html) for more information on what operations can be used when declaring constants. Constants are valid for the entire time a program runs, within the scope in which they were declared. This property makes constants useful for values in your application domain that multiple parts of the program might need to know about, such as the maximum number of points any player of a game is allowed to earn, or the speed of light. Naming hardcoded values used throughout your program as constants is useful in conveying the meaning of that value to future maintainers of the code. It also helps to have only one place in your code that you would need to change if the hardcoded value needed to be updated in the future. As you saw in the guessing game tutorial in [Chapter 2](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number) , you can declare a new variable with the same name as a previous variable. Rustaceans say that the first variable is _shadowed_ by the second, which means that the second variable is what the compiler will see when you use the name of the variable. In effect, the second variable overshadows the first, taking any uses of the variable name to itself until either it itself is shadowed or the scope ends. We can shadow a variable by using the same variable’s name and repeating the use of the `let` keyword as follows: Filename: src/main.rs fn main() { let x = 5; let x = x + 1; { let x = x * 2; println!("The value of x in the inner scope is: {x}"); } println!("The value of x is: {x}"); } This program first binds `x` to a value of `5`. Then, it creates a new variable `x` by repeating `let x =`, taking the original value and adding `1` so that the value of `x` is `6`. Then, within an inner scope created with the curly brackets, the third `let` statement also shadows `x` and creates a new variable, multiplying the previous value by `2` to give `x` a value of `12`. When that scope is over, the inner shadowing ends and `x` returns to being `6`. When we run this program, it will output the following: $ cargo run Compiling variables v0.1.0 (file:///projects/variables) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s Running `target/debug/variables` The value of x in the inner scope is: 12 The value of x is: 6 Shadowing is different from marking a variable as `mut` because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the `let` keyword. By using `let`, we can perform a few transformations on a value but have the variable be immutable after those transformations have completed. The other difference between `mut` and shadowing is that because we’re effectively creating a new variable when we use the `let` keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, and then we want to store that input as a number: fn main() { let spaces = " "; let spaces = spaces.len(); } The first `spaces` variable is a string type, and the second `spaces` variable is a number type. Shadowing thus spares us from having to come up with different names, such as `spaces_str` and `spaces_num`; instead, we can reuse the simpler `spaces` name. However, if we try to use `mut` for this, as shown here, we’ll get a compile-time error: fn main() { let mut spaces = " "; spaces = spaces.len(); } The error says we’re not allowed to mutate a variable’s type: $ cargo run Compiling variables v0.1.0 (file:///projects/variables) error[E0308]: mismatched types --> src/main.rs:3:14 | 2 | let mut spaces = " "; | ----- expected due to this value 3 | spaces = spaces.len(); | ^^^^^^^^^^^^ expected `&str`, found `usize` For more information about this error, try `rustc --explain E0308`. error: could not compile `variables` (bin "variables") due to 1 previous error Now that we’ve explored how variables work, let’s look at more data types they can have. --- # std::str - Rust [Module str](https://doc.rust-lang.org/stable/std/str/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module str Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#224) Expand description Utilities for the `str` primitive type. _[See also the `str` primitive type](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") ._ Modules[§](https://doc.rust-lang.org/stable/std/str/index.html#modules) ------------------------------------------------------------------------ [pattern](https://doc.rust-lang.org/stable/std/str/pattern/index.html "mod std::str::pattern") Experimental The string Pattern API. Structs[§](https://doc.rust-lang.org/stable/std/str/index.html#structs) ------------------------------------------------------------------------ [Bytes](https://doc.rust-lang.org/stable/std/str/struct.Bytes.html "struct std::str::Bytes") An iterator over the bytes of a string slice. [CharIndices](https://doc.rust-lang.org/stable/std/str/struct.CharIndices.html "struct std::str::CharIndices") An iterator over the [`char`](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") s of a string slice, and their positions. [Chars](https://doc.rust-lang.org/stable/std/str/struct.Chars.html "struct std::str::Chars") An iterator over the [`char`](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") s of a string slice. [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") An iterator of [`u16`](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive u16") over the string encoded as UTF-16. [EscapeDebug](https://doc.rust-lang.org/stable/std/str/struct.EscapeDebug.html "struct std::str::EscapeDebug") The return type of [`str::escape_debug`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.escape_debug "method str::escape_debug") . [EscapeDefault](https://doc.rust-lang.org/stable/std/str/struct.EscapeDefault.html "struct std::str::EscapeDefault") The return type of [`str::escape_default`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.escape_default "method str::escape_default") . [EscapeUnicode](https://doc.rust-lang.org/stable/std/str/struct.EscapeUnicode.html "struct std::str::EscapeUnicode") The return type of [`str::escape_unicode`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.escape_unicode "method str::escape_unicode") . [Lines](https://doc.rust-lang.org/stable/std/str/struct.Lines.html "struct std::str::Lines") An iterator over the lines of a string, as string slices. [LinesAny](https://doc.rust-lang.org/stable/std/str/struct.LinesAny.html "struct std::str::LinesAny") Deprecated Created with the method [`lines_any`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.lines_any "method str::lines_any") . [MatchIndices](https://doc.rust-lang.org/stable/std/str/struct.MatchIndices.html "struct std::str::MatchIndices") Created with the method [`match_indices`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.match_indices "method str::match_indices") . [Matches](https://doc.rust-lang.org/stable/std/str/struct.Matches.html "struct std::str::Matches") Created with the method [`matches`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.matches "method str::matches") . [ParseBoolError](https://doc.rust-lang.org/stable/std/str/struct.ParseBoolError.html "struct std::str::ParseBoolError") An error returned when parsing a `bool` using [`from_str`](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html#tymethod.from_str "associated function std::str::FromStr::from_str") fails [RMatchIndices](https://doc.rust-lang.org/stable/std/str/struct.RMatchIndices.html "struct std::str::RMatchIndices") Created with the method [`rmatch_indices`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.rmatch_indices "method str::rmatch_indices") . [RMatches](https://doc.rust-lang.org/stable/std/str/struct.RMatches.html "struct std::str::RMatches") Created with the method [`rmatches`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.rmatches "method str::rmatches") . [RSplit](https://doc.rust-lang.org/stable/std/str/struct.RSplit.html "struct std::str::RSplit") Created with the method [`rsplit`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplit "method str::rsplit") . [RSplitN](https://doc.rust-lang.org/stable/std/str/struct.RSplitN.html "struct std::str::RSplitN") Created with the method [`rsplitn`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplitn "method str::rsplitn") . [RSplitTerminator](https://doc.rust-lang.org/stable/std/str/struct.RSplitTerminator.html "struct std::str::RSplitTerminator") Created with the method [`rsplit_terminator`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplit_terminator "method str::rsplit_terminator") . [Split](https://doc.rust-lang.org/stable/std/str/struct.Split.html "struct std::str::Split") Created with the method [`split`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split "method str::split") . [SplitAsciiWhitespace](https://doc.rust-lang.org/stable/std/str/struct.SplitAsciiWhitespace.html "struct std::str::SplitAsciiWhitespace") An iterator over the non-ASCII-whitespace substrings of a string, separated by any amount of ASCII whitespace. [SplitInclusive](https://doc.rust-lang.org/stable/std/str/struct.SplitInclusive.html "struct std::str::SplitInclusive") An iterator over the substrings of a string, terminated by a substring matching to a predicate function Unlike `Split`, it contains the matched part as a terminator of the subslice. [SplitN](https://doc.rust-lang.org/stable/std/str/struct.SplitN.html "struct std::str::SplitN") Created with the method [`splitn`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.splitn "method str::splitn") . [SplitTerminator](https://doc.rust-lang.org/stable/std/str/struct.SplitTerminator.html "struct std::str::SplitTerminator") Created with the method [`split_terminator`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.split_terminator "method str::split_terminator") . [SplitWhitespace](https://doc.rust-lang.org/stable/std/str/struct.SplitWhitespace.html "struct std::str::SplitWhitespace") An iterator over the non-whitespace substrings of a string, separated by any amount of whitespace. [Utf8Chunk](https://doc.rust-lang.org/stable/std/str/struct.Utf8Chunk.html "struct std::str::Utf8Chunk") An item returned by the [`Utf8Chunks`](https://doc.rust-lang.org/stable/std/str/struct.Utf8Chunks.html "struct std::str::Utf8Chunks") iterator. [Utf8Chunks](https://doc.rust-lang.org/stable/std/str/struct.Utf8Chunks.html "struct std::str::Utf8Chunks") An iterator used to decode a slice of mostly UTF-8 bytes to string slices ([`&str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") ) and byte slices ([`&[u8]`](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive slice") ). [Utf8Error](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html "struct std::str::Utf8Error") Errors which can occur when attempting to interpret a sequence of [`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") as a string. Traits[§](https://doc.rust-lang.org/stable/std/str/index.html#traits) ---------------------------------------------------------------------- [FromStr](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html "trait std::str::FromStr") Parse a value from a string Functions[§](https://doc.rust-lang.org/stable/std/str/index.html#functions) ---------------------------------------------------------------------------- [from\_boxed\_utf8\_unchecked](https://doc.rust-lang.org/stable/std/str/fn.from_boxed_utf8_unchecked.html "fn std::str::from_boxed_utf8_unchecked") ⚠ Converts a boxed slice of bytes to a boxed string slice without checking that the string contains valid UTF-8. [from\_utf8](https://doc.rust-lang.org/stable/std/str/fn.from_utf8.html "fn std::str::from_utf8") Converts a slice of bytes to a string slice. [from\_utf8\_mut](https://doc.rust-lang.org/stable/std/str/fn.from_utf8_mut.html "fn std::str::from_utf8_mut") Converts a mutable slice of bytes to a mutable string slice. [from\_utf8\_unchecked](https://doc.rust-lang.org/stable/std/str/fn.from_utf8_unchecked.html "fn std::str::from_utf8_unchecked") ⚠ Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8. [from\_utf8\_unchecked\_mut](https://doc.rust-lang.org/stable/std/str/fn.from_utf8_unchecked_mut.html "fn std::str::from_utf8_unchecked_mut") ⚠ Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8; mutable version. [from\_raw\_parts](https://doc.rust-lang.org/stable/std/str/fn.from_raw_parts.html "fn std::str::from_raw_parts") ⚠Experimental Creates a `&str` from a pointer and a length. [from\_raw\_parts\_mut](https://doc.rust-lang.org/stable/std/str/fn.from_raw_parts_mut.html "fn std::str::from_raw_parts_mut") ⚠Experimental Creates a `&mut str` from a pointer and a length. --- # Type aliases - The Rust Reference Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Reference ================== [](https://doc.rust-lang.org/stable/reference/print.html "Print this book") [](https://github.com/rust-lang/reference/ "Git repository") [](https://github.com/rust-lang/reference/edit/master/src/items/type-aliases.md "Suggest an edit") [\[items.type\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type "items.type") [\[items.type.syntax\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.syntax "items.type.syntax") **Syntax** [TypeAlias](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#railroad-TypeAlias) →     type [IDENTIFIER](https://doc.rust-lang.org/stable/reference/identifiers.html#grammar-IDENTIFIER) [GenericParams](https://doc.rust-lang.org/stable/reference/items/generics.html#grammar-GenericParams) ? ( : [TypeParamBounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#grammar-TypeParamBounds) )?         [WhereClause](https://doc.rust-lang.org/stable/reference/items/generics.html#grammar-WhereClause) ?         ( \= [Type](https://doc.rust-lang.org/stable/reference/types.html#grammar-Type) [WhereClause](https://doc.rust-lang.org/stable/reference/items/generics.html#grammar-WhereClause) ? )? ; Show Railroad TypeAlias type IDENTIFIER GenericParams : TypeParamBounds WhereClause \= Type WhereClause ; [\[items.type.intro\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.intro "items.type.intro") A _type alias_ defines a new name for an existing [type](https://doc.rust-lang.org/stable/reference/types.html) in the [type namespace](https://doc.rust-lang.org/stable/reference/names/namespaces.html) of the module or block where it is located. Type aliases are declared with the keyword `type`. Every value has a single, specific type, but may implement several different traits, and may be compatible with several different type constraints. For example, the following defines the type `Point` as a synonym for the type `(u8, u8)`, the type of pairs of unsigned 8 bit integers: #![allow(unused)] fn main() { type Point = (u8, u8); let p: Point = (41, 68); } [\[items.type.constructor-alias\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.constructor-alias "items.type.constructor-alias") A type alias to a tuple-struct or unit-struct cannot be used to qualify that type’s constructor: #![allow(unused)] fn main() { struct MyStruct(u32); use MyStruct as UseAlias; type TypeAlias = MyStruct; let _ = UseAlias(5); // OK let _ = TypeAlias(5); // Doesn't work } [\[items.type.associated-type\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.associated-type "items.type.associated-type") A type alias, when not used as an [associated type](https://doc.rust-lang.org/stable/reference/items/associated-items.html#associated-types) , must include a [Type](https://doc.rust-lang.org/stable/reference/types.html#grammar-Type) and may not include [TypeParamBounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#grammar-TypeParamBounds) . [\[items.type.associated-trait\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.associated-trait "items.type.associated-trait") A type alias, when used as an [associated type](https://doc.rust-lang.org/stable/reference/items/associated-items.html#associated-types) in a [trait](https://doc.rust-lang.org/stable/reference/items/traits.html) , must not include a [Type](https://doc.rust-lang.org/stable/reference/types.html#grammar-Type) specification but may include [TypeParamBounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#grammar-TypeParamBounds) . [\[items.type.associated-impl\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.associated-impl "items.type.associated-impl") A type alias, when used as an [associated type](https://doc.rust-lang.org/stable/reference/items/associated-items.html#associated-types) in a [trait impl](https://doc.rust-lang.org/stable/reference/items/implementations.html#trait-implementations) , must include a [Type](https://doc.rust-lang.org/stable/reference/types.html#grammar-Type) specification and may not include [TypeParamBounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#grammar-TypeParamBounds) . [\[items.type.deprecated\]](https://doc.rust-lang.org/stable/reference/items/type-aliases.html#r-items.type.deprecated "items.type.deprecated") Where clauses before the equals sign on a type alias in a [trait impl](https://doc.rust-lang.org/stable/reference/items/implementations.html#trait-implementations) (like `type TypeAlias where T: Foo = Bar`) are deprecated. Where clauses after the equals sign (like `type TypeAlias = Bar where T: Foo`) are preferred. --- # static - Rust [static](https://doc.rust-lang.org/stable/std/keyword.static.html#) -------------------------------------------------------------------- Keyword static Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1639) Expand description A static item is a value which is valid for the entire duration of your program (a `'static` lifetime). On the surface, `static` items seem very similar to [`const`](https://doc.rust-lang.org/stable/std/keyword.const.html) s: both contain a value, both require type annotations and both can only be initialized with constant functions and values. However, `static`s are notably different in that they represent a location in memory. That means that you can have references to `static` items and potentially even modify them, making them essentially global variables. Static items do not call [`drop`](https://doc.rust-lang.org/stable/std/mem/fn.drop.html "fn std::mem::drop") at the end of the program. There are two types of `static` items: those declared in association with the [`mut`](https://doc.rust-lang.org/stable/std/keyword.mut.html) keyword and those without. Static items cannot be moved: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.static.html# "This example deliberately fails to compile") static VEC: Vec = vec![]; fn move_vec(v: Vec) -> Vec { v } // This line causes an error move_vec(VEC); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++static+VEC:+Vec%3Cu32%3E+=+vec!%5B%5D;%0A++++%0A++++fn+move_vec(v:+Vec%3Cu32%3E)+-%3E+Vec%3Cu32%3E+%7B%0A++++++++v%0A++++%7D%0A++++%0A++++//+This+line+causes+an+error%0A++++move_vec(VEC);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.static.html#simple-statics) Simple `static`s --------------------------------------------------------------------------------------------- Accessing non-[`mut`](https://doc.rust-lang.org/stable/std/keyword.mut.html) `static` items is considered safe, but some restrictions apply. Most notably, the type of a `static` value needs to implement the [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") trait, ruling out interior mutability containers like [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") . See the [Reference](https://doc.rust-lang.org/stable/reference/items/static-items.html) for more information. static FOO: [i32; 5] = [1, 2, 3, 4, 5]; let r1 = &FOO as *const _; let r2 = &FOO as *const _; // With a strictly read-only static, references will have the same address assert_eq!(r1, r2); // A static item can be used just like a variable in many cases println!("{FOO:?}"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++static+FOO:+%5Bi32;+5%5D+=+%5B1,+2,+3,+4,+5%5D;%0A++++%0A++++let+r1+=+%26FOO+as+*const+_;%0A++++let+r2+=+%26FOO+as+*const+_;%0A++++//+With+a+strictly+read-only+static,+references+will+have+the+same+address%0A++++assert_eq!(r1,+r2);%0A++++//+A+static+item+can+be+used+just+like+a+variable+in+many+cases%0A++++println!(%22%7BFOO:?%7D%22);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.static.html#mutable-statics) Mutable `static`s ----------------------------------------------------------------------------------------------- If a `static` item is declared with the [`mut`](https://doc.rust-lang.org/stable/std/keyword.mut.html) keyword, then it is allowed to be modified by the program. However, accessing mutable `static`s can cause undefined behavior in a number of ways, for example due to data races in a multithreaded context. As such, all accesses to mutable `static`s require an [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html) block. When possible, it’s often better to use a non-mutable `static` with an interior mutable type such as [`Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html "struct std::sync::Mutex") , [`OnceLock`](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html "struct std::sync::OnceLock") , or an [atomic](https://doc.rust-lang.org/stable/std/sync/atomic/index.html "mod std::sync::atomic") . Despite their unsafety, mutable `static`s are necessary in many contexts: they can be used to represent global state shared by the whole program or in [`extern`](https://doc.rust-lang.org/stable/std/keyword.extern.html) blocks to bind to variables from C libraries. In an [`extern`](https://doc.rust-lang.org/stable/std/keyword.extern.html) block: unsafe extern "C" { static mut ERROR_MESSAGE: *mut std::os::raw::c_char; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++unsafe+extern+%22C%22+%7B%0A++++++++static+mut+ERROR_MESSAGE:+*mut+std::os::raw::c_char;%0A++++%7D%0A%7D&edition=2024 "Run code") Mutable `static`s, just like simple `static`s, have some restrictions that apply to them. See the [Reference](https://doc.rust-lang.org/stable/reference/items/static-items.html) for more information. --- # unsafe - Rust [unsafe](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#) -------------------------------------------------------------------- Keyword unsafe Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2306) Expand description Code or interfaces whose [memory safety](https://doc.rust-lang.org/stable/book/ch19-01-unsafe-rust.html) cannot be verified by the type system. The `unsafe` keyword has two uses: * to declare the existence of contracts the compiler can’t check (`unsafe fn` and `unsafe trait`), * and to declare that a programmer has checked that these contracts have been upheld (`unsafe {}` and `unsafe impl`, but also `unsafe fn` – see below). [§](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#unsafe-abilities) Unsafe abilities ----------------------------------------------------------------------------------------------- **No matter what, Safe Rust can’t cause Undefined Behavior**. This is referred to as [soundness](https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library) : a well-typed program actually has the desired properties. The [Nomicon](https://doc.rust-lang.org/stable/nomicon/safe-unsafe-meaning.html) has a more detailed explanation on the subject. To ensure soundness, Safe Rust is restricted enough that it can be automatically checked. Sometimes, however, it is necessary to write code that is correct for reasons which are too clever for the compiler to understand. In those cases, you need to use Unsafe Rust. Here are the abilities Unsafe Rust has in addition to Safe Rust: * Dereference [raw pointers](https://doc.rust-lang.org/stable/reference/types/pointer.html) * Implement `unsafe` [`trait`](https://doc.rust-lang.org/stable/std/keyword.trait.html) s * Call `unsafe` functions * Mutate [`static`](https://doc.rust-lang.org/stable/std/keyword.static.html) s (including [`extern`](https://doc.rust-lang.org/stable/std/keyword.extern.html) al ones) * Access fields of [`union`](https://doc.rust-lang.org/stable/std/keyword.union.html) s However, this extra power comes with extra responsibilities: it is now up to you to ensure soundness. The `unsafe` keyword helps by clearly marking the pieces of code that need to worry about this. ### [§](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#the-different-meanings-of-unsafe) The different meanings of `unsafe` Not all uses of `unsafe` are equivalent: some are here to mark the existence of a contract the programmer must check, others are to say “I have checked the contract, go ahead and do this”. The following [discussion on Rust Internals](https://internals.rust-lang.org/t/what-does-unsafe-mean/6696) has more in-depth explanations about this but here is a summary of the main points: * `unsafe fn`: calling this function means abiding by a contract the compiler cannot enforce. * `unsafe trait`: implementing the [`trait`](https://doc.rust-lang.org/stable/std/keyword.trait.html) means abiding by a contract the compiler cannot enforce. * `unsafe {}`: the contract necessary to call the operations inside the block has been checked by the programmer and is guaranteed to be respected. * `unsafe impl`: the contract necessary to implement the trait has been checked by the programmer and is guaranteed to be respected. See the [Rustonomicon](https://doc.rust-lang.org/stable/nomicon/index.html) and the [Reference](https://doc.rust-lang.org/stable/reference/unsafety.html) for more information. [§](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#examples) Examples ------------------------------------------------------------------------------- ### [§](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#marking-elements-as-unsafe) Marking elements as `unsafe` `unsafe` can be used on functions. Note that functions and statics declared in [`extern`](https://doc.rust-lang.org/stable/std/keyword.extern.html) blocks are implicitly marked as `unsafe` (but not functions declared as `extern "something" fn ...`). Mutable statics are always unsafe, wherever they are declared. Methods can also be declared as `unsafe`: static mut FOO: &str = "hello"; unsafe fn unsafe_fn() {} unsafe extern "C" { fn unsafe_extern_fn(); static BAR: *mut u32; } trait SafeTraitWithUnsafeMethod { unsafe fn unsafe_method(&self); } struct S; impl S { unsafe fn unsafe_method_on_struct() {} } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++static+mut+FOO:+%26str+=+%22hello%22;%0A++++%0A++++unsafe+fn+unsafe_fn()+%7B%7D%0A++++%0A++++unsafe+extern+%22C%22+%7B%0A++++++++fn+unsafe_extern_fn();%0A++++++++static+BAR:+*mut+u32;%0A++++%7D%0A++++%0A++++trait+SafeTraitWithUnsafeMethod+%7B%0A++++++++unsafe+fn+unsafe_method(%26self);%0A++++%7D%0A++++%0A++++struct+S;%0A++++%0A++++impl+S+%7B%0A++++++++unsafe+fn+unsafe_method_on_struct()+%7B%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Traits can also be declared as `unsafe`: unsafe trait UnsafeTrait {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++unsafe+trait+UnsafeTrait+%7B%7D%0A%7D&edition=2024 "Run code") Since `unsafe fn` and `unsafe trait` indicate that there is a safety contract that the compiler cannot enforce, documenting it is important. The standard library has many examples of this, like the following which is an extract from [`Vec::set_len`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.set_len "method std::vec::Vec::set_len") . The `# Safety` section explains the contract that must be fulfilled to safely call the function. [ⓘ](https://doc.rust-lang.org/stable/std/keyword.unsafe.html# "This example is not tested") /// Forces the length of the vector to `new_len`. /// /// This is a low-level operation that maintains none of the normal /// invariants of the type. Normally changing the length of a vector /// is done using one of the safe operations instead, such as /// `truncate`, `resize`, `extend`, or `clear`. /// /// # Safety /// /// - `new_len` must be less than or equal to `capacity()`. /// - The elements at `old_len..new_len` must be initialized. pub unsafe fn set_len(&mut self, new_len: usize) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++///+Forces+the+length+of+the+vector+to+%60new_len%60.%0A++++///%0A++++///+This+is+a+low-level+operation+that+maintains+none+of+the+normal%0A++++///+invariants+of+the+type.+Normally+changing+the+length+of+a+vector%0A++++///+is+done+using+one+of+the+safe+operations+instead,+such+as%0A++++///+%60truncate%60,+%60resize%60,+%60extend%60,+or+%60clear%60.%0A++++///%0A++++///+%23+Safety%0A++++///%0A++++///+-+%60new_len%60+must+be+less+than+or+equal+to+%60capacity()%60.%0A++++///+-+The+elements+at+%60old_len..new_len%60+must+be+initialized.%0A++++pub+unsafe+fn+set_len(%26mut+self,+new_len:+usize)%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#using-unsafe--blocks-and-impls) Using `unsafe {}` blocks and `impl`s Performing `unsafe` operations requires an `unsafe {}` block: #![deny(unsafe_op_in_unsafe_fn)] /// Dereference the given pointer. /// /// # Safety /// /// `ptr` must be aligned and must not be dangling. unsafe fn deref_unchecked(ptr: *const i32) -> i32 { // SAFETY: the caller is required to ensure that `ptr` is aligned and dereferenceable. unsafe { *ptr } } let a = 3; let b = &a as *const _; // SAFETY: `a` has not been dropped and references are always aligned, // so `b` is a valid address. unsafe { assert_eq!(*b, deref_unchecked(b)); }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%23!%5Bdeny(unsafe_op_in_unsafe_fn)%5D%0A%0A%0Afn+main()+%7B%0A++++///+Dereference+the+given+pointer.%0A++++///%0A++++///+%23+Safety%0A++++///%0A++++///+%60ptr%60+must+be+aligned+and+must+not+be+dangling.%0A++++unsafe+fn+deref_unchecked(ptr:+*const+i32)+-%3E+i32+%7B%0A++++++++//+SAFETY:+the+caller+is+required+to+ensure+that+%60ptr%60+is+aligned+and+dereferenceable.%0A++++++++unsafe+%7B+*ptr+%7D%0A++++%7D%0A++++%0A++++let+a+=+3;%0A++++let+b+=+%26a+as+*const+_;%0A++++//+SAFETY:+%60a%60+has+not+been+dropped+and+references+are+always+aligned,%0A++++//+so+%60b%60+is+a+valid+address.%0A++++unsafe+%7B+assert_eq!(*b,+deref_unchecked(b));+%7D;%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/keyword.unsafe.html#unsafe-and-traits) `unsafe` and traits The interactions of `unsafe` and traits can be surprising, so let us contrast the two combinations of safe `fn` in `unsafe trait` and `unsafe fn` in safe trait using two examples: /// # Safety /// /// `make_even` must return an even number. unsafe trait MakeEven { fn make_even(&self) -> i32; } // SAFETY: Our `make_even` always returns something even. unsafe impl MakeEven for i32 { fn make_even(&self) -> i32 { self << 1 } } fn use_make_even(x: impl MakeEven) { if x.make_even() % 2 == 1 { // SAFETY: this can never happen, because all `MakeEven` implementations // ensure that `make_even` returns something even. unsafe { std::hint::unreachable_unchecked() }; } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++///+%23+Safety%0A++++///%0A++++///+%60make_even%60+must+return+an+even+number.%0A++++unsafe+trait+MakeEven+%7B%0A++++++++fn+make_even(%26self)+-%3E+i32;%0A++++%7D%0A++++%0A++++//+SAFETY:+Our+%60make_even%60+always+returns+something+even.%0A++++unsafe+impl+MakeEven+for+i32+%7B%0A++++++++fn+make_even(%26self)+-%3E+i32+%7B%0A++++++++++++self+%3C%3C+1%0A++++++++%7D%0A++++%7D%0A++++%0A++++fn+use_make_even(x:+impl+MakeEven)+%7B%0A++++++++if+x.make_even()+%25+2+==+1+%7B%0A++++++++++++//+SAFETY:+this+can+never+happen,+because+all+%60MakeEven%60+implementations%0A++++++++++++//+ensure+that+%60make_even%60+returns+something+even.%0A++++++++++++unsafe+%7B+std::hint::unreachable_unchecked()+%7D;%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Note how the safety contract of the trait is upheld by the implementation, and is itself used to uphold the safety contract of the unsafe function `unreachable_unchecked` called by `use_make_even`. `make_even` itself is a safe function because its _callers_ do not have to worry about any contract, only the _implementation_ of `MakeEven` is required to uphold a certain contract. `use_make_even` is safe because it can use the promise made by `MakeEven` implementations to uphold the safety contract of the `unsafe fn unreachable_unchecked` it calls. It is also possible to have `unsafe fn` in a regular safe `trait`: #![deny(unsafe_op_in_unsafe_fn)] trait Indexable { const LEN: usize; /// # Safety /// /// The caller must ensure that `idx < LEN`. unsafe fn idx_unchecked(&self, idx: usize) -> i32; } // The implementation for `i32` doesn't need to do any contract reasoning. impl Indexable for i32 { const LEN: usize = 1; /// See `Indexable` for the safety contract. unsafe fn idx_unchecked(&self, idx: usize) -> i32 { debug_assert_eq!(idx, 0); *self } } // The implementation for arrays exploits the function contract to // make use of `get_unchecked` on slices and avoid a run-time check. impl Indexable for [i32; 42] { const LEN: usize = 42; /// See `Indexable` for the safety contract. unsafe fn idx_unchecked(&self, idx: usize) -> i32 { // SAFETY: As per this trait's documentation, the caller ensures // that `idx < 42`. unsafe { *self.get_unchecked(idx) } } } // The implementation for the never type declares a length of 0, // which means `idx_unchecked` can never be called. impl Indexable for ! { const LEN: usize = 0; /// See `Indexable` for the safety contract. unsafe fn idx_unchecked(&self, idx: usize) -> i32 { // SAFETY: As per this trait's documentation, the caller ensures // that `idx < 0`, which is impossible, so this is dead code. unsafe { std::hint::unreachable_unchecked() } } } fn use_indexable(x: I, idx: usize) -> i32 { if idx < I::LEN { // SAFETY: We have checked that `idx < I::LEN`. unsafe { x.idx_unchecked(idx) } } else { panic!("index out-of-bounds") } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(never_type)%5D%0A%0A%23!%5Bdeny(unsafe_op_in_unsafe_fn)%5D%0A%0A%0Afn+main()+%7B%0A++++trait+Indexable+%7B%0A++++++++const+LEN:+usize;%0A++++%0A++++++++///+%23+Safety%0A++++++++///%0A++++++++///+The+caller+must+ensure+that+%60idx+%3C+LEN%60.%0A++++++++unsafe+fn+idx_unchecked(%26self,+idx:+usize)+-%3E+i32;%0A++++%7D%0A++++%0A++++//+The+implementation+for+%60i32%60+doesn%27t+need+to+do+any+contract+reasoning.%0A++++impl+Indexable+for+i32+%7B%0A++++++++const+LEN:+usize+=+1;%0A++++%0A++++++++///+See+%60Indexable%60+for+the+safety+contract.%0A++++++++unsafe+fn+idx_unchecked(%26self,+idx:+usize)+-%3E+i32+%7B%0A++++++++++++debug_assert_eq!(idx,+0);%0A++++++++++++*self%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+The+implementation+for+arrays+exploits+the+function+contract+to%0A++++//+make+use+of+%60get_unchecked%60+on+slices+and+avoid+a+run-time+check.%0A++++impl+Indexable+for+%5Bi32;+42%5D+%7B%0A++++++++const+LEN:+usize+=+42;%0A++++%0A++++++++///+See+%60Indexable%60+for+the+safety+contract.%0A++++++++unsafe+fn+idx_unchecked(%26self,+idx:+usize)+-%3E+i32+%7B%0A++++++++++++//+SAFETY:+As+per+this+trait%27s+documentation,+the+caller+ensures%0A++++++++++++//+that+%60idx+%3C+42%60.%0A++++++++++++unsafe+%7B+*self.get_unchecked(idx)+%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+The+implementation+for+the+never+type+declares+a+length+of+0,%0A++++//+which+means+%60idx_unchecked%60+can+never+be+called.%0A++++impl+Indexable+for+!+%7B%0A++++++++const+LEN:+usize+=+0;%0A++++%0A++++++++///+See+%60Indexable%60+for+the+safety+contract.%0A++++++++unsafe+fn+idx_unchecked(%26self,+idx:+usize)+-%3E+i32+%7B%0A++++++++++++//+SAFETY:+As+per+this+trait%27s+documentation,+the+caller+ensures%0A++++++++++++//+that+%60idx+%3C+0%60,+which+is+impossible,+so+this+is+dead+code.%0A++++++++++++unsafe+%7B+std::hint::unreachable_unchecked()+%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++fn+use_indexable%3CI:+Indexable%3E(x:+I,+idx:+usize)+-%3E+i32+%7B%0A++++++++if+idx+%3C+I::LEN+%7B%0A++++++++++++//+SAFETY:+We+have+checked+that+%60idx+%3C+I::LEN%60.%0A++++++++++++unsafe+%7B+x.idx_unchecked(idx)+%7D%0A++++++++%7D+else+%7B%0A++++++++++++panic!(%22index+out-of-bounds%22)%0A++++++++%7D%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") This time, `use_indexable` is safe because it uses a run-time check to discharge the safety contract of `idx_unchecked`. Implementing `Indexable` is safe because when writing `idx_unchecked`, we don’t have to worry: our _callers_ need to discharge a proof obligation (like `use_indexable` does), but the _implementation_ of `get_unchecked` has no proof obligation to contend with. Of course, the implementation may choose to call other unsafe operations, and then it needs an `unsafe` _block_ to indicate it discharged the proof obligations of its callees. For that purpose it can make use of the contract that all its callers must uphold – the fact that `idx < LEN`. Note that unlike normal `unsafe fn`, an `unsafe fn` in a trait implementation does not get to just pick an arbitrary safety contract! It _has_ to use the safety contract defined by the trait (or one with weaker preconditions). Formally speaking, an `unsafe fn` in a trait is a function with _preconditions_ that go beyond those encoded by the argument types (such as `idx < LEN`), whereas an `unsafe trait` can declare that some of its functions have _postconditions_ that go beyond those encoded in the return type (such as returning an even integer). If a trait needs a function with both extra precondition and extra postcondition, then it needs an `unsafe fn` in an `unsafe trait`. --- # enum - Rust [enum](https://doc.rust-lang.org/stable/std/keyword.enum.html#) ---------------------------------------------------------------- Keyword enum Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#436) Expand description A type that can be any one of several variants. Enums in Rust are similar to those of other compiled languages like C, but have important differences that make them considerably more powerful. What Rust calls enums are more commonly known as [Algebraic Data Types](https://en.wikipedia.org/wiki/Algebraic_data_type) if you’re coming from a functional programming background. The important detail is that each enum variant can have data to go along with it. enum SimpleEnum { FirstVariant, SecondVariant, ThirdVariant, } enum Location { Unknown, Anonymous, Known(Coord), } enum ComplexEnum { Nothing, Something(u32), LotsOfThings { usual_struct_stuff: bool, blah: String, } } enum EmptyEnum { } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Coord;%0A++++enum+SimpleEnum+%7B%0A++++++++FirstVariant,%0A++++++++SecondVariant,%0A++++++++ThirdVariant,%0A++++%7D%0A++++%0A++++enum+Location+%7B%0A++++++++Unknown,%0A++++++++Anonymous,%0A++++++++Known(Coord),%0A++++%7D%0A++++%0A++++enum+ComplexEnum+%7B%0A++++++++Nothing,%0A++++++++Something(u32),%0A++++++++LotsOfThings+%7B%0A++++++++++++usual_struct_stuff:+bool,%0A++++++++++++blah:+String,%0A++++++++%7D%0A++++%7D%0A++++%0A++++enum+EmptyEnum+%7B+%7D%0A%7D&edition=2024 "Run code") The first enum shown is the usual kind of enum you’d find in a C-style language. The second shows off a hypothetical example of something storing location data, with `Coord` being any other type that’s needed, for example a struct. The third example demonstrates the kind of data a variant can store, ranging from nothing, to a tuple, to an anonymous struct. Instantiating enum variants involves explicitly using the enum’s name as its namespace, followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above. When data follows along with a variant, such as with rust’s built-in [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") type, the data is added as the type describes, for example `Option::Some(123)`. The same follows with struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff: true, blah: "hello!".to_string(), }`. Empty Enums are similar to [`!`](https://doc.rust-lang.org/stable/std/primitive.never.html "primitive never") in that they cannot be instantiated at all, and are used mainly to mess with the type system in interesting ways. For more information, take a look at the [Rust Book](https://doc.rust-lang.org/stable/book/ch06-01-defining-an-enum.html) or the [Reference](https://doc.rust-lang.org/stable/reference/items/enumerations.html) --- # fn - Rust [fn](https://doc.rust-lang.org/stable/std/keyword.fn.html#) ------------------------------------------------------------ Keyword fn Copy item path ========================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#561) Expand description A function or function pointer. Functions are the primary way code is executed within Rust. Function blocks, usually just called functions, can be defined in a variety of different places and be assigned many different attributes and modifiers. Standalone functions that just sit within a module not attached to anything else are common, but most functions will end up being inside [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) blocks, either on another type itself, or as a trait impl for that type. fn standalone_function() { // code } pub fn public_thing(argument: bool) -> String { // code } struct Thing { foo: i32, } impl Thing { pub fn new() -> Self { Self { foo: 42, } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+standalone_function()+%7B%0A++++++++//+code%0A++++%7D%0A++++%0A++++pub+fn+public_thing(argument:+bool)+-%3E+String+%7B%0A++++++++//+code%0A++++%22%22.to_string()%0A++++%7D%0A++++%0A++++struct+Thing+%7B%0A++++++++foo:+i32,%0A++++%7D%0A++++%0A++++impl+Thing+%7B%0A++++++++pub+fn+new()+-%3E+Self+%7B%0A++++++++++++Self+%7B%0A++++++++++++++++foo:+42,%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`, functions can also declare a list of type parameters along with trait bounds that they fall into. fn generic_function(x: T) -> (T, T, T) { (x.clone(), x.clone(), x.clone()) } fn generic_where(x: T) -> T where T: std::ops::Add + Copy { x + x + x } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+generic_function%3CT:+Clone%3E(x:+T)+-%3E+(T,+T,+T)+%7B%0A++++++++(x.clone(),+x.clone(),+x.clone())%0A++++%7D%0A++++%0A++++fn+generic_where%3CT%3E(x:+T)+-%3E+T%0A++++++++where+T:+std::ops::Add%3COutput+=+T%3E+%2B+Copy%0A++++%7B%0A++++++++x+%2B+x+%2B+x%0A++++%7D%0A%7D&edition=2024 "Run code") Declaring trait bounds in the angle brackets is functionally identical to using a `where` clause. It’s up to the programmer to decide which works better in each situation, but `where` tends to be better when things get longer than one line. Along with being made public via `pub`, `fn` can also have an [`extern`](https://doc.rust-lang.org/stable/std/keyword.extern.html) added for use in FFI. For more information on the various types of functions and how they’re used, consult the [Rust book](https://doc.rust-lang.org/stable/book/ch03-03-how-functions-work.html) or the [Reference](https://doc.rust-lang.org/stable/reference/items/functions.html) . --- # async - Rust [async](https://doc.rust-lang.org/stable/std/keyword.async.html#) ------------------------------------------------------------------ Keyword async Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#2624) Expand description Returns a [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") instead of blocking the current thread. Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`. As such the code will not be run immediately, but will only be evaluated when the returned future is [`.await`](https://doc.rust-lang.org/stable/std/keyword.await.html) ed. We have written an [async book](https://rust-lang.github.io/async-book/) detailing `async`/`await` and trade-offs compared to using threads. ### [§](https://doc.rust-lang.org/stable/std/keyword.async.html#control-flow) Control Flow [`return`](https://doc.rust-lang.org/stable/std/keyword.return.html) statements and [`?`](https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#r-expr.try) operators within `async` blocks do not cause a return from the parent function; rather, they cause the `Future` returned by the block to return with that value. For example, the following Rust function will return `5`, causing `x` to take the [`!` type](https://doc.rust-lang.org/stable/reference/types/never.html) : #[expect(unused_variables)] fn example() -> i32 { let x = { return 5; }; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bexpect(unused_variables)%5D%0A++++fn+example()+-%3E+i32+%7B%0A++++++++let+x+=+%7B%0A++++++++++++return+5;%0A++++++++%7D;%0A++++%7D%0A%7D&edition=2024 "Run code") In contrast, the following asynchronous function assigns a `Future` to `x`, and only returns `5` when `x` is `.await`ed: async fn example() -> i32 { let x = async { return 5; }; x.await } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++async+fn+example()+-%3E+i32+%7B%0A++++++++let+x+=+async+%7B%0A++++++++++++return+5;%0A++++++++%7D;%0A++++%0A++++++++x.await%0A++++%7D%0A%7D&edition=2024 "Run code") Code using `?` behaves similarly - it causes the `async` block to return a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") without affecting the parent function. Note that you cannot use `break` or `continue` from within an `async` block to affect the control flow of a loop in the parent function. Control flow in `async` blocks is documented further in the [async book](https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks) . ### [§](https://doc.rust-lang.org/stable/std/keyword.async.html#editions) Editions `async` is a keyword from the 2018 edition onwards. It is available for use in stable Rust from version 1.39 onwards. --- # struct - Rust [struct](https://doc.rust-lang.org/stable/std/keyword.struct.html#) -------------------------------------------------------------------- Keyword struct Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1747) Expand description A type that is composed of other types. Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs. struct Regular { field1: f32, field2: String, pub field3: bool } struct Tuple(u32, String); struct Unit; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Regular+%7B%0A++++++++field1:+f32,%0A++++++++field2:+String,%0A++++++++pub+field3:+bool%0A++++%7D%0A++++%0A++++struct+Tuple(u32,+String);%0A++++%0A++++struct+Unit;%0A%7D&edition=2024 "Run code") Regular structs are the most commonly used. Each field defined within them has a name and a type, and once defined can be accessed using `example_struct.field` syntax. The fields of a struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding `pub` to a field makes it visible to code in other modules, as well as allowing it to be directly accessed and modified. Tuple structs are similar to regular structs, but its fields have no names. They are used like tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`, etc, starting at zero. Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are useful when you need to implement a trait on something, but don’t need to store any data inside it. [§](https://doc.rust-lang.org/stable/std/keyword.struct.html#instantiation) Instantiation ----------------------------------------------------------------------------------------- Structs can be instantiated in different ways, all of which can be mixed and matched as needed. The most common way to make a new struct is via a constructor method such as `new()`, but when that isn’t available (or you’re writing the constructor itself), struct literal syntax is used: let example = Foo { field1: 42.0, field2: "blah".to_string(), etc: true, }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Foo+%7B+field1:+f32,+field2:+String,+etc:+bool+%7D%0A++++let+example+=+Foo+%7B%0A++++++++field1:+42.0,%0A++++++++field2:+%22blah%22.to_string(),%0A++++++++etc:+true,%0A++++%7D;%0A%7D&edition=2024 "Run code") It’s only possible to directly instantiate a struct using struct literal syntax when all of its fields are visible to you. There are a handful of shortcuts provided to make writing constructors more convenient, most common of which is the Field Init shorthand. When there is a variable and a field of the same name, the assignment can be simplified from `field: field` into simply `field`. The following example of a hypothetical constructor demonstrates this: struct User { name: String, admin: bool, } impl User { pub fn new(name: String) -> Self { Self { name, admin: false, } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+User+%7B%0A++++++++name:+String,%0A++++++++admin:+bool,%0A++++%7D%0A++++%0A++++impl+User+%7B%0A++++++++pub+fn+new(name:+String)+-%3E+Self+%7B%0A++++++++++++Self+%7B%0A++++++++++++++++name,%0A++++++++++++++++admin:+false,%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Another shortcut for struct instantiation is available, used when you need to make a new struct that has the same values as most of a previous struct of the same type, called struct update syntax: let updated_thing = Foo { field1: "a new value".to_string(), ..thing }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Foo+%7B+field1:+String,+field2:+()+%7D%0A++++let+thing+=+Foo+%7B+field1:+%22%22.to_string(),+field2:+()+%7D;%0A++++let+updated_thing+=+Foo+%7B%0A++++++++field1:+%22a+new+value%22.to_string(),%0A++++++++..thing%0A++++%7D;%0A%7D&edition=2024 "Run code") Tuple structs are instantiated in the same way as tuples themselves, except with the struct’s name as a prefix: `Foo(123, false, 0.1)`. Empty structs are instantiated with just their name, and don’t need anything else. `let thing = EmptyStruct;` [§](https://doc.rust-lang.org/stable/std/keyword.struct.html#style-conventions) Style conventions ------------------------------------------------------------------------------------------------- Structs are always written in UpperCamelCase, with few exceptions. While the trailing comma on a struct’s list of fields can be omitted, it’s usually kept for convenience in adding and removing fields down the line. For more information on structs, take a look at the [Rust Book](https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html) or the [Reference](https://doc.rust-lang.org/stable/reference/items/structs.html) . --- # std::pin - Rust [Module pin](https://doc.rust-lang.org/stable/std/pin/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module pin Copy item path ========================= 1.33.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#322) Expand description Types that pin data to a location in memory. It is sometimes useful to be able to rely upon a certain value not being able to _move_, in the sense that its address in memory cannot change. This is useful especially when there are one or more [_pointers_](https://doc.rust-lang.org/stable/std/primitive.pointer.html "primitive pointer") pointing at that value. The ability to rely on this guarantee that the value a [pointer](https://doc.rust-lang.org/stable/std/primitive.pointer.html "primitive pointer") is pointing at (its **pointee**) will 1. Not be _moved_ out of its memory location 2. More generally, remain _valid_ at that same memory location is called “pinning.” We would say that a value which satisfies these guarantees has been “pinned,” in that it has been permanently (until the end of its lifespan) attached to its location in memory, as though pinned to a pinboard. Pinning a value is an incredibly useful building block for [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code to be able to reason about whether a raw pointer to the pinned value is still valid. [As we’ll see later](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") , once a value is pinned, it is necessarily valid at its memory location until the end of its lifespan. This concept of “pinning” is necessary to implement safe interfaces on top of things like self-referential types and intrusive data structures which cannot currently be modeled in fully safe Rust using only borrow-checked [references](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") . “Pinning” allows us to put a _value_ which exists at some location in memory into a state where safe code cannot _move_ that value to a different location in memory or otherwise invalidate it at its current location (unless it implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , which we will [talk about below](https://doc.rust-lang.org/stable/std/pin/index.html#unpin "mod std::pin") ). Anything that wants to interact with the pinned value in a way that has the potential to violate these guarantees must promise that it will not actually violate them, using the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") keyword to mark that such a promise is upheld by the user and not the compiler. In this way, we can allow other [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code to rely on any pointers that point to the pinned value to be valid to dereference while it is pinned. Note that as long as you don’t use [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") , it’s impossible to create or misuse a pinned value in a way that is unsound. See the documentation of [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") for more information on the practicalities of how to pin a value and how to use that pinned value from a user’s perspective without using [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") . The rest of this documentation is intended to be the source of truth for users of [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") that are implementing the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") pieces of an interface that relies on pinning for validity; users of [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") in safe code do not need to read it in detail. There are several sections to this documentation: * [What is “_moving_”?](https://doc.rust-lang.org/stable/std/pin/index.html#what-is-moving "mod std::pin") * [What is “pinning”?](https://doc.rust-lang.org/stable/std/pin/index.html#what-is-pinning "mod std::pin") * [Address sensitivity, AKA “when do we need pinning?”](https://doc.rust-lang.org/stable/std/pin/index.html#address-sensitive-values-aka-when-we-need-pinning "mod std::pin") * [Examples of types with address-sensitive states](https://doc.rust-lang.org/stable/std/pin/index.html#examples-of-address-sensitive-types) * [Self-referential struct](https://doc.rust-lang.org/stable/std/pin/index.html#a-self-referential-struct) * [Intrusive, doubly-linked list](https://doc.rust-lang.org/stable/std/pin/index.html#an-intrusive-doubly-linked-list) * [Subtle details and the `Drop` guarantee](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") [§](https://doc.rust-lang.org/stable/std/pin/index.html#what-is-moving) What is “_moving_”? ------------------------------------------------------------------------------------------- When we say a value is _moved_, we mean that the compiler copies, byte-for-byte, the value from one location to another. In a purely mechanical sense, this is identical to [`Copy`](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") ing a value from one place in memory to another. In Rust, “move” carries with it the semantics of ownership transfer from one variable to another, which is the key difference between a [`Copy`](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") and a move. For the purposes of this module’s documentation, however, when we write _move_ in italics, we mean _specifically_ that the value has _moved_ in the mechanical sense of being located at a new place in memory. All values in Rust are trivially _moveable_. This means that the address at which a value is located is not necessarily stable in between borrows. The compiler is allowed to _move_ a value to a new address without running any code to notify that value that its address has changed. Although the compiler will not insert memory _moves_ where no semantic move has occurred, there are many places where a value _may_ be moved. For example, when doing assignment or passing a value into a function. #[derive(Default)] struct AddrTracker(Option); impl AddrTracker { // If we haven't checked the addr of self yet, store the current // address. If we have, confirm that the current address is the same // as it was last time, or else panic. fn check_for_move(&mut self) { let current_addr = self as *mut Self as usize; match self.0 { None => self.0 = Some(current_addr), Some(prev_addr) => assert_eq!(prev_addr, current_addr), } } } // Create a tracker and store the initial address let mut tracker = AddrTracker::default(); tracker.check_for_move(); // Here we shadow the variable. This carries a semantic move, and may therefore also // come with a mechanical memory *move* let mut tracker = tracker; // May panic! // tracker.check_for_move(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(Default)%5D%0A++++struct+AddrTracker(Option%3Cusize%3E);%0A++++%0A++++impl+AddrTracker+%7B%0A++++++++//+If+we+haven%27t+checked+the+addr+of+self+yet,+store+the+current%0A++++++++//+address.+If+we+have,+confirm+that+the+current+address+is+the+same%0A++++++++//+as+it+was+last+time,+or+else+panic.%0A++++++++fn+check_for_move(%26mut+self)+%7B%0A++++++++++++let+current_addr+=+self+as+*mut+Self+as+usize;%0A++++++++++++match+self.0+%7B%0A++++++++++++++++None+=%3E+self.0+=+Some(current_addr),%0A++++++++++++++++Some(prev_addr)+=%3E+assert_eq!(prev_addr,+current_addr),%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+Create+a+tracker+and+store+the+initial+address%0A++++let+mut+tracker+=+AddrTracker::default();%0A++++tracker.check_for_move();%0A++++%0A++++//+Here+we+shadow+the+variable.+This+carries+a+semantic+move,+and+may+therefore+also%0A++++//+come+with+a+mechanical+memory+*move*%0A++++let+mut+tracker+=+tracker;%0A%7D&edition=2024 "Run code") In this sense, Rust does not guarantee that `check_for_move()` will never panic, because the compiler is permitted to _move_ `tracker` in many situations. Common smart-pointer types such as [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) and [`&mut T`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") also allow _moving_ the underlying _value_ they point at: you can move out of a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) , or you can use [`mem::replace`](https://doc.rust-lang.org/stable/std/mem/fn.replace.html "fn std::mem::replace") to move a `T` out of a [`&mut T`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") . Therefore, putting a value (such as `tracker` above) behind a pointer isn’t enough on its own to ensure that its address does not change. [§](https://doc.rust-lang.org/stable/std/pin/index.html#what-is-pinning) What is “pinning”? ------------------------------------------------------------------------------------------- We say that a value has been _pinned_ when it has been put into a state where it is guaranteed to remain _located at the same place in memory_ from the time it is pinned until its [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") is called. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#address-sensitive-values-aka-when-we-need-pinning) Address-sensitive values, AKA “when we need pinning” Most values in Rust are entirely okay with being _moved_ around at-will. Types for which it is _always_ the case that _any_ value of that type can be _moved_ at-will should implement [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , which we will discuss more [below](https://doc.rust-lang.org/stable/std/pin/index.html#unpin "mod std::pin") . [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") is specifically targeted at allowing the implementation of _safe interfaces_ around types which have some state during which they become “address-sensitive.” A value in such an “address-sensitive” state is _not_ okay with being _moved_ around at-will. Such a value must stay _un-moved_ and valid during the address-sensitive portion of its lifespan because some interface is relying on those invariants to be true in order for its implementation to be sound. As a motivating example of a type which may become address-sensitive, consider a type which contains a pointer to another piece of its own data, _i.e._ a “self-referential” type. In order for such a type to be implemented soundly, the pointer which points into `self`’s data must be proven valid whenever it is accessed. But if that value is _moved_, the pointer will still point to the old address where the value was located and not into the new location of `self`, thus becoming invalid. A key example of such self-referential types are the state machines generated by the compiler to implement [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") for `async fn`s. Such types that have an _address-sensitive_ state usually follow a lifecycle that looks something like so: 1. A value is created which can be freely moved around. * e.g. calling an async function which returns a state machine implementing [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") 2. An operation causes the value to depend on its own address not changing * e.g. calling [`poll`](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll "future::Future::poll") for the first time on the produced [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") 3. Further pieces of the safe interface of the type use internal [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") operations which assume that the address of the value is stable * e.g. subsequent calls to [`poll`](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll "future::Future::poll") 4. Before the value is invalidated (e.g. deallocated), it is _dropped_, giving it a chance to notify anything with pointers to itself that those pointers will be invalidated * e.g. [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") ping the [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") [1](https://doc.rust-lang.org/stable/std/pin/index.html#fn1) There are two possible ways to ensure the invariants required for 2. and 3. above (which apply to any address-sensitive type, not just self-referential types) do not get broken. 1. Have the value detect when it is moved and update all the pointers that point to itself. 2. Guarantee that the address of the value does not change (and that memory is not re-used for anything else) during the time that the pointers to it are expected to be valid to dereference. Since, as we discussed, Rust can move values without notifying them that they have moved, the first option is ruled out. In order to implement the second option, we must in some way enforce its key invariant, _i.e._ prevent the value from being _moved_ or otherwise invalidated (you may notice this sounds an awful lot like the definition of _pinning_ a value). There are a few ways one might be able to enforce this invariant in Rust: 1. Offer a wholly `unsafe` API to interact with the object, thus requiring every caller to uphold the invariant themselves 2. Store the value that must not be moved behind a carefully managed pointer internal to the object 3. Leverage the type system to encode and enforce this invariant by presenting a restricted API surface to interact with _any_ object that requires these invariants The first option is quite obviously undesirable, as the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") ty of the interface will become viral throughout all code that interacts with the object. The second option is a viable solution to the problem for some use cases, in particular for self-referential types. Under this model, any type that has an address sensitive state would ultimately store its data in something like a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) , carefully manage internal access to that data to ensure no _moves_ or other invalidation occurs, and finally provide a safe interface on top. There are a couple of linked disadvantages to using this model. The most significant is that each individual object must assume it is _on its own_ to ensure that its data does not become _moved_ or otherwise invalidated. Since there is no shared contract between values of different types, an object cannot assume that others interacting with it will properly respect the invariants around interacting with its data and must therefore protect it from everyone. Because of this, _composition_ of address-sensitive types requires at least a level of pointer indirection each time a new object is added to the mix (and, practically, a heap allocation). Although there were other reasons as well, this issue of expensive composition is the key thing that drove Rust towards adopting a different model. It is particularly a problem when one considers, for example, the implications of composing together the [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") s which will eventually make up an asynchronous task (including address-sensitive `async fn` state machines). It is plausible that there could be many layers of [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") s composed together, including multiple layers of `async fn`s handling different parts of a task. It was deemed unacceptable to force indirection and allocation for each layer of composition in this case. [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") is an implementation of the third option. It allows us to solve the issues discussed with the second option by building a _shared contractual language_ around the guarantees of “pinning” data. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#using-pinptr-to-pin-values) Using [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") to pin values In order to pin a value, we wrap a _pointer to that value_ (of some type `Ptr`) in a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") . [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") can wrap any pointer type, forming a promise that the **pointee** will not be _moved_ or [otherwise invalidated](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") . We call such a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") \-wrapped pointer a **pinning pointer,** (or pinning reference, or pinning `Box`, etc.) because its existence is the thing that is conceptually pinning the underlying pointee in place: it is the metaphorical “pin” securing the data in place on the pinboard (in memory). Notice that the thing wrapped by [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") is not the value which we want to pin itself, but rather a pointer to that value! A [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") does not pin the `Ptr`; instead, it pins the pointer’s _**pointee** value_. #### [§](https://doc.rust-lang.org/stable/std/pin/index.html#pinning-as-a-library-contract) Pinning as a library contract Pinning does not require nor make use of any compiler “magic”[2](https://doc.rust-lang.org/stable/std/pin/index.html#fn2) , only a specific contract between the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") parts of a library API and its users. It is important to stress this point as a user of the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") parts of the [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") API. Practically, this means that performing the mechanics of “pinning” a value by creating a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") to it _does not_ actually change the way the compiler behaves towards the inner value! It is possible to use incorrect [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code to create a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") to a value which does not actually satisfy the invariants that a pinned value must satisfy, and in this way lead to undefined behavior even in (from that point) fully safe code. Similarly, using [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") , one may get access to a bare [`&mut T`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") from a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") and use that to invalidly _move_ the pinned value out. It is the job of the user of the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") parts of the [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") API to ensure these invariants are not violated. This differs from e.g. [`UnsafeCell`](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html "struct std::cell::UnsafeCell") which changes the semantics of a program’s compiled output. A [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") is a handle to a value which we have promised we will not move out of, but Rust still considers all values themselves to be fundamentally moveable through, _e.g._ assignment or [`mem::replace`](https://doc.rust-lang.org/stable/std/mem/fn.replace.html "fn std::mem::replace") . #### [§](https://doc.rust-lang.org/stable/std/pin/index.html#how-pin-prevents-misuse-in-safe-code) How [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") prevents misuse in safe code In order to accomplish the goal of pinning the pointee value, [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") restricts access to the wrapped `Ptr` type in safe code. Specifically, [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") disallows the ability to access the wrapped pointer in ways that would allow the user to _move_ the underlying pointee value or otherwise re-use that memory for something else without using [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") . For example, a [`Pin<&mut T>`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") makes it impossible to obtain the wrapped `[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T` safely because through that `[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T` it would be possible to _move_ the underlying value out of the pointer with [`mem::replace`](https://doc.rust-lang.org/stable/std/mem/fn.replace.html "fn std::mem::replace") , etc. As discussed above, this promise must be upheld manually by [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code which interacts with the [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") so that other [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code can rely on the pointee value being _un-moved_ and valid. Interfaces that operate on values which are in an address-sensitive state accept an argument like `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T>` or `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") >` to indicate this contract to the caller. [As discussed below](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") , opting in to using pinning guarantees in the interface of an address-sensitive type has consequences for the implementation of some safe traits on that type as well. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#interaction-between-deref-and-pinptr) Interaction between [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") and [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") Since [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") can wrap any pointer type, it uses [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") and [`DerefMut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "ops::DerefMut") in order to identify the type of the pinned pointee data and provide (restricted) access to it. A [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") where [`Ptr: Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") is a “`Ptr`\-style pinning pointer” to a pinned [`Ptr::Target`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "ops::Deref::Target") – so, a `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") >` is an owned, pinning pointer to a pinned `T`, and a `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[Rc](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "rc::Rc") >` is a reference-counted, pinning pointer to a pinned `T`. [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") also uses the [`::Target`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "ops::Deref::Target") type information to modify the interface it is allowed to provide for interacting with that data (for example, when a pinning pointer points at pinned data which implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , as [discussed below](https://doc.rust-lang.org/stable/std/pin/index.html#unpin "mod std::pin") ). [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") requires that implementations of [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") and [`DerefMut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "ops::DerefMut") on `Ptr` return a pointer to the pinned data directly and do not _move_ out of the `self` parameter during their implementation of [`DerefMut::deref_mut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html#tymethod.deref_mut "method std::ops::DerefMut::deref_mut") . It is unsound for [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code to wrap pointer types with such “malicious” implementations of [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") ; see [`Pin::new_unchecked`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.new_unchecked "associated function std::pin::Pin::new_unchecked") for details. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#fixing-addrtracker) Fixing `AddrTracker` The guarantee of a stable address is necessary to make our `AddrTracker` example work. When `check_for_move` sees a `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <&mut AddrTracker>`, it can safely assume that value will exist at that same address until said value goes out of scope, and thus multiple calls to it _cannot_ panic. use std::marker::PhantomPinned; use std::pin::Pin; use std::pin::pin; #[derive(Default)] struct AddrTracker { prev_addr: Option, // remove auto-implemented `Unpin` bound to mark this type as having some // address-sensitive state. This is essential for our expected pinning // guarantees to work, and is discussed more below. _pin: PhantomPinned, } impl AddrTracker { fn check_for_move(self: Pin<&mut Self>) { let current_addr = &*self as *const Self as usize; match self.prev_addr { None => { // SAFETY: we do not move out of self let self_data_mut = unsafe { self.get_unchecked_mut() }; self_data_mut.prev_addr = Some(current_addr); }, Some(prev_addr) => assert_eq!(prev_addr, current_addr), } } } // 1. Create the value, not yet in an address-sensitive state let tracker = AddrTracker::default(); // 2. Pin the value by putting it behind a pinning pointer, thus putting // it into an address-sensitive state let mut ptr_to_pinned_tracker: Pin<&mut AddrTracker> = pin!(tracker); ptr_to_pinned_tracker.as_mut().check_for_move(); // Trying to access `tracker` or pass `ptr_to_pinned_tracker` to anything that requires // mutable access to a non-pinned version of it will no longer compile // 3. We can now assume that the tracker value will never be moved, thus // this will never panic! ptr_to_pinned_tracker.as_mut().check_for_move(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::marker::PhantomPinned;%0A++++use+std::pin::Pin;%0A++++use+std::pin::pin;%0A++++%0A++++%23%5Bderive(Default)%5D%0A++++struct+AddrTracker+%7B%0A++++++++prev_addr:+Option%3Cusize%3E,%0A++++++++//+remove+auto-implemented+%60Unpin%60+bound+to+mark+this+type+as+having+some%0A++++++++//+address-sensitive+state.+This+is+essential+for+our+expected+pinning%0A++++++++//+guarantees+to+work,+and+is+discussed+more+below.%0A++++++++_pin:+PhantomPinned,%0A++++%7D%0A++++%0A++++impl+AddrTracker+%7B%0A++++++++fn+check_for_move(self:+Pin%3C%26mut+Self%3E)+%7B%0A++++++++++++let+current_addr+=+%26*self+as+*const+Self+as+usize;%0A++++++++++++match+self.prev_addr+%7B%0A++++++++++++++++None+=%3E+%7B%0A++++++++++++++++++++//+SAFETY:+we+do+not+move+out+of+self%0A++++++++++++++++++++let+self_data_mut+=+unsafe+%7B+self.get_unchecked_mut()+%7D;%0A++++++++++++++++++++self_data_mut.prev_addr+=+Some(current_addr);%0A++++++++++++++++%7D,%0A++++++++++++++++Some(prev_addr)+=%3E+assert_eq!(prev_addr,+current_addr),%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+1.+Create+the+value,+not+yet+in+an+address-sensitive+state%0A++++let+tracker+=+AddrTracker::default();%0A++++%0A++++//+2.+Pin+the+value+by+putting+it+behind+a+pinning+pointer,+thus+putting%0A++++//+it+into+an+address-sensitive+state%0A++++let+mut+ptr_to_pinned_tracker:+Pin%3C%26mut+AddrTracker%3E+=+pin!(tracker);%0A++++ptr_to_pinned_tracker.as_mut().check_for_move();%0A++++%0A++++//+Trying+to+access+%60tracker%60+or+pass+%60ptr_to_pinned_tracker%60+to+anything+that+requires%0A++++//+mutable+access+to+a+non-pinned+version+of+it+will+no+longer+compile%0A++++%0A++++//+3.+We+can+now+assume+that+the+tracker+value+will+never+be+moved,+thus%0A++++//+this+will+never+panic!%0A++++ptr_to_pinned_tracker.as_mut().check_for_move();%0A%7D&edition=2024 "Run code") Note that this invariant is enforced by simply making it impossible to call code that would perform a move on the pinned value. This is the case since the only way to access that pinned value is through the pinning `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T>`, which in turn restricts our access. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#unpin) [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") The vast majority of Rust types have no address-sensitive states. These types implement the [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") auto-trait, which cancels the restrictive effects of [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") when the _pointee_ type `T` is [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") . When [`T: Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") >` functions identically to a non-pinning [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) ; similarly, `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T>` would impose no additional restrictions above a regular [`&mut T`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") . The idea of this trait is to alleviate the reduced ergonomics of APIs that require the use of [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") for soundness for some types, but which also want to be used by other types that don’t care about pinning. The prime example of such an API is [`Future::poll`](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll "method std::future::Future::poll") . There are many [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") types that don’t care about pinning. These futures can implement [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") and therefore get around the pinning related restrictions in the API, while still allowing the subset of [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") s which _do_ require pinning to be implemented soundly. Note that the interaction between a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") and [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") is through the type of the **pointee** value, [`::Target`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "ops::Deref::Target") . Whether the `Ptr` type itself implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") does not affect the behavior of a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") . For example, whether or not [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") is [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") has no effect on the behavior of `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") >`, because `T` is the type of the pointee value, not [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") . So, whether `T` implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") is the thing that will affect the behavior of the `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") >`. Builtin types that are [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") include all of the primitive types, like [`bool`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") , [`i32`](https://doc.rust-lang.org/stable/std/primitive.i32.html "primitive i32") , and [`f32`](https://doc.rust-lang.org/stable/std/primitive.f32.html "primitive f32") , references (`[&](https://doc.rust-lang.org/stable/std/primitive.reference.html "shared reference") T` and `[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") T`), etc., as well as many core and standard library types like [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) , [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "String") , and more. These types are marked [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") because they do not have an address-sensitive state like the ones we discussed above. If they did have such a state, those parts of their interface would be unsound without being expressed through pinning, and they would then need to not implement [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") . The compiler is free to take the conservative stance of marking types as [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") so long as all of the types that compose its fields are also [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") . This is because if a type implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , then it is unsound for that type’s implementation to rely on pinning-related guarantees for soundness, _even_ when viewed through a “pinning” pointer! It is the responsibility of the implementor of a type that relies upon pinning for soundness to ensure that type is _not_ marked as [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") by adding [`PhantomPinned`](https://doc.rust-lang.org/stable/std/marker/struct.PhantomPinned.html "struct std::marker::PhantomPinned") field. This is exactly what we did with our `AddrTracker` example above. Without doing this, you _must not_ rely on pinning-related guarantees to apply to your type! If you really need to pin a value of a foreign or built-in type that implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , you’ll need to create your own wrapper type around the [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") type you want to pin and then opt-out of [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") using [`PhantomPinned`](https://doc.rust-lang.org/stable/std/marker/struct.PhantomPinned.html "struct std::marker::PhantomPinned") . Exposing access to the inner field which you want to remain pinned must then be carefully considered as well! Remember, exposing a method that gives access to a `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") InnerT>` where `InnerT: [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") ` would allow safe code to trivially move the inner value out of that pinning pointer, which is precisely what you’re seeking to prevent! Exposing a field of a pinned value through a pinning pointer is called “projecting” a pin, and the more general case of deciding in which cases a pin should be able to be projected or not is called “structural pinning.” We will go into more detail about this [below](https://doc.rust-lang.org/stable/std/pin/index.html#projections-and-structural-pinning "mod std::pin") . [§](https://doc.rust-lang.org/stable/std/pin/index.html#examples-of-address-sensitive-types) Examples of address-sensitive types -------------------------------------------------------------------------------------------------------------------------------- ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#a-self-referential-struct) A self-referential struct Self-referential structs are the simplest kind of address-sensitive type. It is often useful for a struct to hold a pointer back into itself, which allows the program to efficiently track subsections of the struct. Below, the `slice` field is a pointer into the `data` field, which we could imagine being used to track a sliding window of `data` in parser code. As mentioned before, this pattern is also used extensively by compiler-generated [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") s. use std::pin::Pin; use std::marker::PhantomPinned; use std::ptr::NonNull; /// This is a self-referential struct because `self.slice` points into `self.data`. struct Unmovable { /// Backing buffer. data: [u8; 64], /// Points at `self.data` which we know is itself non-null. Raw pointer because we can't do /// this with a normal reference. slice: NonNull<[u8]>, /// Suppress `Unpin` so that this cannot be moved out of a `Pin` once constructed. _pin: PhantomPinned, } impl Unmovable { /// Creates a new `Unmovable`. /// /// To ensure the data doesn't move we place it on the heap behind a pinning Box. /// Note that the data is pinned, but the `Pin>` which is pinning it can /// itself still be moved. This is important because it means we can return the pinning /// pointer from the function, which is itself a kind of move! fn new() -> Pin> { let res = Unmovable { data: [0; 64], // We only create the pointer once the data is in place // otherwise it will have already moved before we even started. slice: NonNull::from(&[]), _pin: PhantomPinned, }; // First we put the data in a box, which will be its final resting place let mut boxed = Box::new(res); // Then we make the slice field point to the proper part of that boxed data. // From now on we need to make sure we don't move the boxed data. boxed.slice = NonNull::from(&boxed.data); // To do that, we pin the data in place by pointing to it with a pinning // (`Pin`-wrapped) pointer. // // `Box::into_pin` makes existing `Box` pin the data in-place without moving it, // so we can safely do this now *after* inserting the slice pointer above, but we have // to take care that we haven't performed any other semantic moves of `res` in between. let pin = Box::into_pin(boxed); // Now we can return the pinned (through a pinning Box) data pin } } let unmovable: Pin> = Unmovable::new(); // The inner pointee `Unmovable` struct will now never be allowed to move. // Meanwhile, we are free to move the pointer around. let mut still_unmoved = unmovable; assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data)); // We cannot mutably dereference a `Pin` unless the pointee is `Unpin` or we use unsafe. // Since our type doesn't implement `Unpin`, this will fail to compile. // let mut new_unmoved = Unmovable::new(); // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::pin::Pin;%0A++++use+std::marker::PhantomPinned;%0A++++use+std::ptr::NonNull;%0A++++%0A++++///+This+is+a+self-referential+struct+because+%60self.slice%60+points+into+%60self.data%60.%0A++++struct+Unmovable+%7B%0A++++++++///+Backing+buffer.%0A++++++++data:+%5Bu8;+64%5D,%0A++++++++///+Points+at+%60self.data%60+which+we+know+is+itself+non-null.+Raw+pointer+because+we+can%27t+do%0A++++++++///+this+with+a+normal+reference.%0A++++++++slice:+NonNull%3C%5Bu8%5D%3E,%0A++++++++///+Suppress+%60Unpin%60+so+that+this+cannot+be+moved+out+of+a+%60Pin%60+once+constructed.%0A++++++++_pin:+PhantomPinned,%0A++++%7D%0A++++%0A++++impl+Unmovable+%7B%0A++++++++///+Creates+a+new+%60Unmovable%60.%0A++++++++///%0A++++++++///+To+ensure+the+data+doesn%27t+move+we+place+it+on+the+heap+behind+a+pinning+Box.%0A++++++++///+Note+that+the+data+is+pinned,+but+the+%60Pin%3CBox%3CSelf%3E%3E%60+which+is+pinning+it+can%0A++++++++///+itself+still+be+moved.+This+is+important+because+it+means+we+can+return+the+pinning%0A++++++++///+pointer+from+the+function,+which+is+itself+a+kind+of+move!%0A++++++++fn+new()+-%3E+Pin%3CBox%3CSelf%3E%3E+%7B%0A++++++++++++let+res+=+Unmovable+%7B%0A++++++++++++++++data:+%5B0;+64%5D,%0A++++++++++++++++//+We+only+create+the+pointer+once+the+data+is+in+place%0A++++++++++++++++//+otherwise+it+will+have+already+moved+before+we+even+started.%0A++++++++++++++++slice:+NonNull::from(%26%5B%5D),%0A++++++++++++++++_pin:+PhantomPinned,%0A++++++++++++%7D;%0A++++++++++++//+First+we+put+the+data+in+a+box,+which+will+be+its+final+resting+place%0A++++++++++++let+mut+boxed+=+Box::new(res);%0A++++%0A++++++++++++//+Then+we+make+the+slice+field+point+to+the+proper+part+of+that+boxed+data.%0A++++++++++++//+From+now+on+we+need+to+make+sure+we+don%27t+move+the+boxed+data.%0A++++++++++++boxed.slice+=+NonNull::from(%26boxed.data);%0A++++%0A++++++++++++//+To+do+that,+we+pin+the+data+in+place+by+pointing+to+it+with+a+pinning%0A++++++++++++//+(%60Pin%60-wrapped)+pointer.%0A++++++++++++//%0A++++++++++++//+%60Box::into_pin%60+makes+existing+%60Box%60+pin+the+data+in-place+without+moving+it,%0A++++++++++++//+so+we+can+safely+do+this+now+*after*+inserting+the+slice+pointer+above,+but+we+have%0A++++++++++++//+to+take+care+that+we+haven%27t+performed+any+other+semantic+moves+of+%60res%60+in+between.%0A++++++++++++let+pin+=+Box::into_pin(boxed);%0A++++%0A++++++++++++//+Now+we+can+return+the+pinned+(through+a+pinning+Box)+data%0A++++++++++++pin%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+unmovable:+Pin%3CBox%3CUnmovable%3E%3E+=+Unmovable::new();%0A++++%0A++++//+The+inner+pointee+%60Unmovable%60+struct+will+now+never+be+allowed+to+move.%0A++++//+Meanwhile,+we+are+free+to+move+the+pointer+around.%0A++++%23%5Ballow(unused_mut)%5D%0A++++let+mut+still_unmoved+=+unmovable;%0A++++assert_eq!(still_unmoved.slice,+NonNull::from(%26still_unmoved.data));%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#an-intrusive-doubly-linked-list) An intrusive, doubly-linked list In an intrusive doubly-linked list, the collection itself does not own the memory in which each of its elements is stored. Instead, each client is free to allocate space for elements it adds to the list in whichever manner it likes, including on the stack! Elements can live on a stack frame that lives shorter than the collection does provided the elements that live in a given stack frame are removed from the list before going out of scope. To make such an intrusive data structure work, every element stores pointers to its predecessor and successor within its own data, rather than having the list structure itself managing those pointers. It is in this sense that the structure is “intrusive”: the details of how an element is stored within the larger structure “intrudes” on the implementation of the element type itself! The full implementation details of such a data structure are outside the scope of this documentation, but we will discuss how [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") can help to do so. Using such an intrusive pattern, elements may only be added when they are pinned. If we think about the consequences of adding non-pinned values to such a list, this becomes clear: _Moving_ or otherwise invalidating an element’s data would invalidate the pointers back to it which are stored in the elements ahead and behind it. Thus, in order to soundly dereference the pointers stored to the next and previous elements, we must satisfy the guarantee that nothing has invalidated those pointers (which point to data that we do not own). Moreover, the [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") implementation of each element must in some way notify its predecessor and successor elements that it should be removed from the list before it is fully destroyed, otherwise the pointers back to it would again become invalidated. Crucially, this means we have to be able to rely on [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") always being called before an element is invalidated. If an element could be deallocated or otherwise invalidated without calling [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") , the pointers to it stored in its neighboring elements would become invalid, which would break the data structure. Therefore, pinning data also comes with [the “`Drop` guarantee”](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") . [§](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee) Subtle details and the `Drop` guarantee -------------------------------------------------------------------------------------------------------------------------------------- The purpose of pinning is not _just_ to prevent a value from being _moved_, but more generally to be able to rely on the pinned value _remaining valid **at a specific place**_ in memory. To do so, pinning a value adds an _additional_ invariant that must be upheld in order for use of the pinned data to be valid, on top of the ones that must be upheld for a non-pinned value of the same type to be valid: From the moment a value is pinned by constructing a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") ning pointer to it, that value must _remain, **valid**_, at that same address in memory, _until its [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") handler is called._ There is some subtlety to this which we have not yet talked about in detail. The invariant described above means that, yes, 1. The value must not be moved out of its location in memory but it also implies that, 2. The memory location that stores the value must not get invalidated or otherwise repurposed during the lifespan of the pinned value until its [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") returns or panics This point is subtle but required for intrusive data structures to be implemented soundly. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#drop-guarantee) `Drop` guarantee There needs to be a way for a pinned value to notify any code that is relying on its pinned status that it is about to be destroyed. In this way, the dependent code can remove the pinned value’s address from its data structures or otherwise change its behavior with the knowledge that it can no longer rely on that value existing at the location it was pinned to. Thus, in any situation where we may want to overwrite a pinned value, that value’s [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") must be called beforehand (unless the pinned value implements [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , in which case we can ignore all of [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") ’s guarantees, as usual). The most common storage-reuse situations occur when a value on the stack is destroyed as part of a function return and when heap storage is freed. In both cases, [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") gets run for us by Rust when using standard safe code. However, for manual heap allocations or otherwise custom-allocated storage, [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code must make sure to call [`ptr::drop_in_place`](https://doc.rust-lang.org/stable/std/ptr/fn.drop_in_place.html "fn std::ptr::drop_in_place") before deallocating and re-using said storage. In addition, storage “re-use”/invalidation can happen even if no storage is (de-)allocated. For example, if we had an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") which contained a `Some(v)` where `v` is pinned, then `v` would be invalidated by setting that option to `None`. Similarly, if a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "Vec") was used to store pinned values and [`Vec::set_len`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.set_len "Vec::set_len") was used to manually “kill” some elements of a vector, all of the items “killed” would become invalidated, which would be _undefined behavior_ if those items were pinned. Both of these cases are somewhat contrived, but it is crucial to remember that [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") ned data _must_ be [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") ped before it is invalidated; not just to prevent memory leaks, but as a matter of soundness. As a corollary, the following code can _never_ be made safe: // Pin something inside a `ManuallyDrop`. This is fine on its own. let mut pin: Pin>> = Box::pin(ManuallyDrop::new(Type)); // However, creating a pinning mutable reference to the type *inside* // the `ManuallyDrop` is not! let inner: Pin<&mut Type> = unsafe { Pin::map_unchecked_mut(pin.as_mut(), |x| &mut **x) }; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::mem::ManuallyDrop;%0A++++use+std::pin::Pin;%0A++++struct+Type;%0A++++//+Pin+something+inside+a+%60ManuallyDrop%60.+This+is+fine+on+its+own.%0A++++let+mut+pin:+Pin%3CBox%3CManuallyDrop%3CType%3E%3E%3E+=+Box::pin(ManuallyDrop::new(Type));%0A++++%0A++++//+However,+creating+a+pinning+mutable+reference+to+the+type+*inside*%0A++++//+the+%60ManuallyDrop%60+is+not!%0A++++let+inner:+Pin%3C%26mut+Type%3E+=+unsafe+%7B%0A++++++++Pin::map_unchecked_mut(pin.as_mut(),+%7Cx%7C+%26mut+**x)%0A++++%7D;%0A%7D&edition=2024 "Run code") Because [`mem::ManuallyDrop`](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "struct std::mem::ManuallyDrop") inhibits the destructor of `Type`, it won’t get run when the `[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "Box") <[ManuallyDrop](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "ManuallyDrop") >` is dropped, thus violating the drop guarantee of the `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") Type>>`. Of course, _leaking_ memory in such a way that its underlying storage will never get invalidated or re-used is still fine: [`mem::forget`](https://doc.rust-lang.org/stable/std/mem/fn.forget.html "mem::forget") ing a [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) prevents its storage from ever getting re-used, so the [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") guarantee is still satisfied. [§](https://doc.rust-lang.org/stable/std/pin/index.html#implementing-an-address-sensitive-type) Implementing an address-sensitive type. --------------------------------------------------------------------------------------------------------------------------------------- This section goes into detail on important considerations for implementing your own address-sensitive types, which are different from merely using [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") in a generic way. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#implementing-drop-for-types-with-address-sensitive-states) Implementing [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") for types with address-sensitive states The [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") function takes [`&mut self`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") , but this is called _even if that `self` has been pinned_! Implementing [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") for a type with address-sensitive states requires some care, because if `self` was indeed in an address-sensitive state before [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") was called, it is as if the compiler automatically called [`Pin::get_unchecked_mut`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.get_unchecked_mut "method std::pin::Pin::get_unchecked_mut") . This can never cause a problem in purely safe code because creating a pinning pointer to a type which has an address-sensitive (thus does not implement `Unpin`) requires `unsafe`, but it is important to note that choosing to take advantage of pinning-related guarantees to justify validity in the implementation of your type has consequences for that type’s [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") implementation as well: if an element of your type could have been pinned, you must treat [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") as implicitly taking `self: [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") Self>`. You should implement [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") as follows: impl Drop for Type { fn drop(&mut self) { // `new_unchecked` is okay because we know this value is never used // again after being dropped. inner_drop(unsafe { Pin::new_unchecked(self)}); fn inner_drop(this: Pin<&mut Type>) { // Actual drop code goes here. } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::pin::Pin;%0A++++struct+Type;%0A++++impl+Drop+for+Type+%7B%0A++++++++fn+drop(%26mut+self)+%7B%0A++++++++++++//+%60new_unchecked%60+is+okay+because+we+know+this+value+is+never+used%0A++++++++++++//+again+after+being+dropped.%0A++++++++++++inner_drop(unsafe+%7B+Pin::new_unchecked(self)%7D);%0A++++++++++++fn+inner_drop(this:+Pin%3C%26mut+Type%3E)+%7B%0A++++++++++++++++//+Actual+drop+code+goes+here.%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") The function `inner_drop` has the signature that [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") _should_ have in this situation. This makes sure that you do not accidentally use `self`/`this` in a way that is in conflict with pinning’s invariants. Moreover, if your type is [`#[repr(packed)]`](https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked) , the compiler will automatically move fields around to be able to drop them. It might even do that for fields that happen to be sufficiently aligned. As a consequence, you cannot use pinning with a [`#[repr(packed)]`](https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked) type. #### [§](https://doc.rust-lang.org/stable/std/pin/index.html#implementing-drop-for-pointer-types-which-will-be-used-as-pinning-pointers) Implementing [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") for pointer types which will be used as [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") ning pointers It should further be noted that creating a pinning pointer of some type `Ptr` _also_ carries with it implications on the way that `Ptr` type must implement [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") (as well as [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") and [`DerefMut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "ops::DerefMut") )! When implementing a pointer type that may be used as a pinning pointer, you must also take the same care described above not to _move_ out of or otherwise invalidate the pointee during [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") , [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "ops::Deref") , or [`DerefMut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "ops::DerefMut") implementations. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#assigning-pinned-data) “Assigning” pinned data Although in general it is not valid to swap data or assign through a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") for the same reason that reusing a pinned object’s memory is invalid, it is possible to do validly when implemented with special care for the needs of the exact data structure which is being modified. For example, the assigning function must know how to update all uses of the pinned address (and any other invariants necessary to satisfy validity for that type). For [`Unmovable`](https://doc.rust-lang.org/stable/std/pin/index.html#a-self-referential-struct) (from the example above), we could write an assignment function like so: impl Unmovable { // Copies the contents of `src` into `self`, fixing up the self-pointer // in the process. fn assign(self: Pin<&mut Self>, src: Pin<&mut Self>) { unsafe { let unpinned_self = Pin::into_inner_unchecked(self); let unpinned_src = Pin::into_inner_unchecked(src); *unpinned_self = Self { data: unpinned_src.data, slice: NonNull::from(&mut []), _pin: PhantomPinned, }; let data_ptr = unpinned_src.data.as_ptr() as *const u8; let slice_ptr = unpinned_src.slice.as_ptr() as *const u8; let offset = slice_ptr.offset_from(data_ptr) as usize; let len = unpinned_src.slice.as_ptr().len(); unpinned_self.slice = NonNull::from(&mut unpinned_self.data[offset..offset+len]); } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::pin::Pin;%0A++++use+std::marker::PhantomPinned;%0A++++use+std::ptr::NonNull;%0A++++struct+Unmovable+%7B%0A++++++++data:+%5Bu8;+64%5D,%0A++++++++slice:+NonNull%3C%5Bu8%5D%3E,%0A++++++++_pin:+PhantomPinned,%0A++++%7D%0A++++%0A++++impl+Unmovable+%7B%0A++++++++//+Copies+the+contents+of+%60src%60+into+%60self%60,+fixing+up+the+self-pointer%0A++++++++//+in+the+process.%0A++++++++fn+assign(self:+Pin%3C%26mut+Self%3E,+src:+Pin%3C%26mut+Self%3E)+%7B%0A++++++++++++unsafe+%7B%0A++++++++++++++++let+unpinned_self+=+Pin::into_inner_unchecked(self);%0A++++++++++++++++let+unpinned_src+=+Pin::into_inner_unchecked(src);%0A++++++++++++++++*unpinned_self+=+Self+%7B%0A++++++++++++++++++++data:+unpinned_src.data,%0A++++++++++++++++++++slice:+NonNull::from(%26mut+%5B%5D),%0A++++++++++++++++++++_pin:+PhantomPinned,%0A++++++++++++++++%7D;%0A++++%0A++++++++++++++++let+data_ptr+=+unpinned_src.data.as_ptr()+as+*const+u8;%0A++++++++++++++++let+slice_ptr+=+unpinned_src.slice.as_ptr()+as+*const+u8;%0A++++++++++++++++let+offset+=+slice_ptr.offset_from(data_ptr)+as+usize;%0A++++++++++++++++let+len+=+unpinned_src.slice.as_ptr().len();%0A++++%0A++++++++++++++++unpinned_self.slice+=+NonNull::from(%26mut+unpinned_self.data%5Boffset..offset%2Blen%5D);%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Even though we can’t have the compiler do the assignment for us, it’s possible to write such specialized functions for types that might need it. Note that it _is_ possible to assign generically through a [`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") by way of [`Pin::set()`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.set "method std::pin::Pin::set") . This does not violate any guarantees, since it will run [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") on the pointee value before assigning the new value. Thus, the [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") implementation still has a chance to perform the necessary notifications to dependent values before the memory location of the original pinned value is overwritten. ### [§](https://doc.rust-lang.org/stable/std/pin/index.html#projections-and-structural-pinning) Projections and Structural Pinning With ordinary structs, it is natural that we want to add _projection_ methods that allow borrowing one or more of the inner fields of a struct when the caller has access to a borrow of the whole struct: struct Struct { field: Field, // ... } impl Struct { fn field(&mut self) -> &mut Field { &mut self.field } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Field;%0A++++struct+Struct+%7B%0A++++++++field:+Field,%0A++++++++//+...%0A++++%7D%0A++++%0A++++impl+Struct+%7B%0A++++++++fn+field(%26mut+self)+-%3E+%26mut+Field+%7B+%26mut+self.field+%7D%0A++++%7D%0A%7D&edition=2024 "Run code") When working with address-sensitive types, it’s not obvious what the signature of these functions should be. If `field` takes `self: [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut Struct](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") >`, should it return [`&mut Field`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") or ``[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut Field`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >``? This question also arises with `enum`s and wrapper types like [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) , [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) , and [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") . (This question applies just as well to shared references, but we’ll examine the more common case of mutable references for illustration) It turns out that it’s up to the author of `Struct` to decide which type the “projection” should produce. The choice must be _consistent_ though: if a pin is projected to a field in one place, then it should very likely not be exposed elsewhere without projecting the pin. As the author of a data structure, you get to decide for each field whether pinning “propagates” to this field or not. Pinning that propagates is also called “structural”, because it follows the structure of the type. This choice depends on what guarantees you need from the field for your [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code to work. If the field is itself address-sensitive, or participates in the parent struct’s address sensitivity, it will need to be structurally pinned. A useful test is if [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code that consumes `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut Struct](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") >` also needs to take note of the address of the field itself, it may be evidence that that field is structurally pinned. Unfortunately, there are no hard-and-fast rules. #### [§](https://doc.rust-lang.org/stable/std/pin/index.html#choosing-pinning-not-to-be-structural-for-field) Choosing pinning _not to be_ structural for `field`… While counter-intuitive, it’s often the easier choice: if you do not expose a `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") Field>`, you do not need to be careful about other code moving out of that field, you just have to ensure is that you never create pinning reference to that field. This does of course also mean that if you decide a field does not have structural pinning, you must not write [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") code that assumes (invalidly) that the field _is_ structurally pinned! Fields without structural pinning may have a projection method that turns `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") Struct>` into [`&mut Field`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") : impl Struct { fn field(self: Pin<&mut Self>) -> &mut Field { // This is okay because `field` is never considered pinned, therefore we do not // need to uphold any pinning guarantees for this field in particular. Of course, // we must not elsewhere assume this field *is* pinned if we choose to expose // such a method! unsafe { &mut self.get_unchecked_mut().field } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::pin::Pin;%0A++++type+Field+=+i32;%0A++++struct+Struct+%7B+field:+Field+%7D%0A++++impl+Struct+%7B%0A++++++++fn+field(self:+Pin%3C%26mut+Self%3E)+-%3E+%26mut+Field+%7B%0A++++++++++++//+This+is+okay+because+%60field%60+is+never+considered+pinned,+therefore+we+do+not%0A++++++++++++//+need+to+uphold+any+pinning+guarantees+for+this+field+in+particular.+Of+course,%0A++++++++++++//+we+must+not+elsewhere+assume+this+field+*is*+pinned+if+we+choose+to+expose%0A++++++++++++//+such+a+method!%0A++++++++++++unsafe+%7B+%26mut+self.get_unchecked_mut().field+%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") You may also in this situation `impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for Struct {}` _even if_ the type of `field` is not [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") . Since we have explicitly chosen not to care about pinning guarantees for `field`, the way `field`’s type interacts with pinning is no longer relevant in the context of its use in `Struct`. #### [§](https://doc.rust-lang.org/stable/std/pin/index.html#choosing-pinning-to-be-structural-for-field) Choosing pinning _to be_ structural for `field`… The other option is to decide that pinning is “structural” for `field`, meaning that if the struct is pinned then so is the field. This allows writing a projection that creates a ``[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut Field`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >``, thus witnessing that the field is pinned: impl Struct { fn field(self: Pin<&mut Self>) -> Pin<&mut Field> { // This is okay because `field` is pinned when `self` is. unsafe { self.map_unchecked_mut(|s| &mut s.field) } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::pin::Pin;%0A++++type+Field+=+i32;%0A++++struct+Struct+%7B+field:+Field+%7D%0A++++impl+Struct+%7B%0A++++++++fn+field(self:+Pin%3C%26mut+Self%3E)+-%3E+Pin%3C%26mut+Field%3E+%7B%0A++++++++++++//+This+is+okay+because+%60field%60+is+pinned+when+%60self%60+is.%0A++++++++++++unsafe+%7B+self.map_unchecked_mut(%7Cs%7C+%26mut+s.field)+%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") Structural pinning comes with a few extra requirements: 1. _Structural [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") ._ A struct can be [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") only if all of its structurally-pinned fields are, too. This is [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") ’s behavior by default. However, as a library author, it is your responsibility not to write something like `impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for Struct {}` and then offer a method that provides structural pinning to an inner field of `T`, which may not be [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") ! (Adding _any_ projection operation requires unsafe code, so the fact that [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") is a safe trait does not break the principle that you only have to worry about any of this if you use [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html "keyword unsafe") ) 2. _Pinned Destruction._ As discussed [above](https://doc.rust-lang.org/stable/std/pin/index.html#implementing-drop-for-types-with-address-sensitive-states "mod std::pin") , [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") takes [`&mut self`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") , but the struct (and hence its fields) might have been pinned before. The destructor must be written as if its argument was ``self: [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut Self`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >``, instead. As a consequence, the struct _must not_ be [`#[repr(packed)]`](https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked) . 3. _Structural Notice of Destruction._ You must uphold the [`Drop` guarantee](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") : once your struct is pinned, the struct’s storage cannot be re-used without calling the structurally-pinned fields’ destructors, as well. This can be tricky, as witnessed by [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html) : the destructor of [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html) can fail to call [`drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop "method std::ops::Drop::drop") on all elements if one of the destructors panics. This violates the [`Drop` guarantee](https://doc.rust-lang.org/stable/std/pin/index.html#subtle-details-and-the-drop-guarantee "mod std::pin") , because it can lead to elements being deallocated without their destructor being called. [`VecDeque`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html) has no pinning projections, so its destructor is sound. If it wanted to provide such structural pinning, its destructor would need to abort the process if any of the destructors panicked. 4. You must not offer any other operations that could lead to data being _moved_ out of the structural fields when your type is pinned. For example, if the struct contains an [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") and there is a [`take`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.take "method std::option::Option::take") \-like operation with type ``fn([Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut Struct](https://doc.rust-lang.org/stable/std/primitive.reference.html "mutable reference") >) -> [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") ``, then that operation can be used to move a `T` out of a pinned `Struct` – which means pinning cannot be structural for the field holding this data. For a more complex example of moving data out of a pinned type, imagine if [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") had a method ``fn get_pin_mut(self: [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut Self`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >) -> [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut T`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >``. Then we could do the following: [ⓘ](https://doc.rust-lang.org/stable/std/pin/index.html# "This example deliberately fails to compile") fn exploit_ref_cell(rc: Pin<&mut RefCell>) { // Here we get pinned access to the `T`. let _: Pin<&mut T> = rc.as_mut().get_pin_mut(); // And here we have `&mut T` to the same data. let shared: &RefCell = rc.into_ref().get_ref(); let borrow = shared.borrow_mut(); let content = &mut *borrow; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++use+std::pin::Pin;%0A++++fn+exploit_ref_cell%3CT%3E(rc:+Pin%3C%26mut+RefCell%3CT%3E%3E)+%7B%0A++++++++//+Here+we+get+pinned+access+to+the+%60T%60.%0A++++++++let+_:+Pin%3C%26mut+T%3E+=+rc.as_mut().get_pin_mut();%0A++++%0A++++++++//+And+here+we+have+%60%26mut+T%60+to+the+same+data.%0A++++++++let+shared:+%26RefCell%3CT%3E+=+rc.into_ref().get_ref();%0A++++++++let+borrow+=+shared.borrow_mut();%0A++++++++let+content+=+%26mut+*borrow;%0A++++%7D%0A%7D&edition=2024 "Run code") This is catastrophic: it means we can first pin the content of the [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") (using `[RefCell](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "cell::RefCell") ::get_pin_mut`) and then move that content using the mutable reference we got later. #### [§](https://doc.rust-lang.org/stable/std/pin/index.html#structural-pinning-examples) Structural Pinning examples For a type like [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) , both possibilities (structural pinning or not) make sense. A [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) with structural pinning could have `get_pin`/`get_pin_mut` methods to get pinning references to elements. However, it could _not_ allow calling [`pop`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.pop "Vec::pop") on a pinned [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) because that would move the (structurally pinned) contents! Nor could it allow [`push`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.push "Vec::push") , which might reallocate and thus also move the contents. A [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) without structural pinning could ``impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) ``, because the contents are never pinned and the [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) itself is fine with being moved as well. At that point pinning just has no effect on the vector at all. In the standard library, pointer types generally do not have structural pinning, and thus they do not offer pinning projections. This is why ``[`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) : [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") `` holds for all `T`. It makes sense to do this for pointer types, because moving the [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) does not actually move the `T`: the [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) can be freely movable (aka [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") ) even if the `T` is not. In fact, even ``[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) >`` and ``[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut T`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >`` are always [`Unpin`](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") themselves, for the same reason: their contents (the `T`) are pinned, but the pointers themselves can be moved without moving the pinned data. For both [`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) and ``[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`Box`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html) >``, whether the content is pinned is entirely independent of whether the pointer is pinned, meaning pinning is _not_ structural. When implementing a [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html "future::Future") combinator, you will usually need structural pinning for the nested futures, as you need to get pinning ([`Pin`](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") \-wrapped) references to them to call [`poll`](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll "future::Future::poll") . But if your combinator contains any other data that does not need to be pinned, you can make those fields not structural and hence freely access them with a mutable reference even when you just have ``[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[`&mut Self`](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") >`` (such as in your own [`poll`](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll "future::Future::poll") implementation). * * * 1. Futures themselves do not ever need to notify other bits of code that they are being dropped, however data structures like stack-based intrusive linked lists do. [↩](https://doc.rust-lang.org/stable/std/pin/index.html#fnref1) 2. There is a bit of nuance here that is still being decided about what the aliasing semantics of `Pin<&mut T>` should be, but this is true as of today. [↩](https://doc.rust-lang.org/stable/std/pin/index.html#fnref2) Macros[§](https://doc.rust-lang.org/stable/std/pin/index.html#macros) ---------------------------------------------------------------------- [pin](https://doc.rust-lang.org/stable/std/pin/macro.pin.html "macro std::pin::pin") Constructs a `[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <[&mut](https://doc.rust-lang.org/stable/std/primitive.reference.html "primitive reference") T>`, by pinning a `value: T` locally. Structs[§](https://doc.rust-lang.org/stable/std/pin/index.html#structs) ------------------------------------------------------------------------ [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") A pointer which pins its pointee in place. [UnsafePinned](https://doc.rust-lang.org/stable/std/pin/struct.UnsafePinned.html "struct std::pin::UnsafePinned") Experimental This type provides a way to entirely opt-out of typical aliasing rules; specifically, `&mut UnsafePinned` is not guaranteed to be a unique pointer. This also subsumes the effects of `UnsafeCell`, i.e., `&UnsafePinned` may point to data that is being mutated. Traits[§](https://doc.rust-lang.org/stable/std/pin/index.html#traits) ---------------------------------------------------------------------- [PinCoerceUnsized](https://doc.rust-lang.org/stable/std/pin/trait.PinCoerceUnsized.html "trait std::pin::PinCoerceUnsized") Experimental Trait that indicates that this is a pointer or a wrapper for one, where unsizing can be performed on the pointee when it is pinned. --- # for - Rust [for](https://doc.rust-lang.org/stable/std/keyword.for.html#) -------------------------------------------------------------- Keyword for Copy item path ========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#643) Expand description Iteration with [`in`](https://doc.rust-lang.org/stable/std/keyword.in.html) , trait implementation with [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) , or [higher-ranked trait bounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#higher-ranked-trait-bounds) (`for<'a>`). The `for` keyword is used in many syntactic locations: * `for` is used in for-in-loops (see below). * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) for more info on that). * `for` is also used for [higher-ranked trait bounds](https://doc.rust-lang.org/stable/reference/trait-bounds.html#higher-ranked-trait-bounds) as in `for<'a> &'a T: PartialEq`. for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common practice within Rust, which is to loop over anything that implements [`IntoIterator`](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") until the iterator returned by `.into_iter()` returns `None` (or the loop body uses `break`). for i in 0..5 { println!("{}", i * 2); } for i in std::iter::repeat(5) { println!("turns out {i} never stops being 5"); break; // would loop forever otherwise } 'outer: for x in 5..50 { for y in 0..10 { if x == y { break 'outer; } } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++for+i+in+0..5+%7B%0A++++++++println!(%22%7B%7D%22,+i+*+2);%0A++++%7D%0A++++%0A++++for+i+in+std::iter::repeat(5)+%7B%0A++++++++println!(%22turns+out+%7Bi%7D+never+stops+being+5%22);%0A++++++++break;+//+would+loop+forever+otherwise%0A++++%7D%0A++++%0A++++%27outer:+for+x+in+5..50+%7B%0A++++++++for+y+in+0..10+%7B%0A++++++++++++if+x+==+y+%7B%0A++++++++++++++++break+%27outer;%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") As shown in the example above, `for` loops (along with all other loops) can be tagged, using similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely not a goto. A `for` loop expands as shown: for loop_variable in iterator { code() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+code()+%7B+%7D%0A++++let+iterator+=+0..2;%0A++++for+loop_variable+in+iterator+%7B%0A++++++++code()%0A++++%7D%0A%7D&edition=2024 "Run code") { let result = match IntoIterator::into_iter(iterator) { mut iter => loop { match iter.next() { None => break, Some(loop_variable) => { code(); }, }; }, }; result } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+code()+%7B+%7D%0A++++let+iterator+=+0..2;%0A++++%7B%0A++++++++let+result+=+match+IntoIterator::into_iter(iterator)+%7B%0A++++++++++++mut+iter+=%3E+loop+%7B%0A++++++++++++++++match+iter.next()+%7B%0A++++++++++++++++++++None+=%3E+break,%0A++++++++++++++++++++Some(loop_variable)+=%3E+%7B+code();+%7D,%0A++++++++++++++++%7D;%0A++++++++++++%7D,%0A++++++++%7D;%0A++++++++result%0A++++%7D%0A%7D&edition=2024 "Run code") More details on the functionality shown can be seen at the [`IntoIterator`](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") docs. For more information on for-loops, see the [Rust book](https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#looping-through-a-collection-with-for) or the [Reference](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html#iterator-loops) . See also, [`loop`](https://doc.rust-lang.org/stable/std/keyword.loop.html) , [`while`](https://doc.rust-lang.org/stable/std/keyword.while.html) . --- # loop - Rust [loop](https://doc.rust-lang.org/stable/std/keyword.loop.html#) ---------------------------------------------------------------- Keyword loop Copy item path =========================== [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#952) Expand description Loop indefinitely. `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside it until the code uses `break` or the program exits. loop { println!("hello world forever!"); } let mut i = 1; loop { println!("i is {i}"); if i > 100 { break; } i *= 2; } assert_eq!(i, 128); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++loop+%7B%0A++++++++println!(%22hello+world+forever!%22);%0A++++break;%0A++++%7D%0A++++%0A++++let+mut+i+=+1;%0A++++loop+%7B%0A++++++++println!(%22i+is+%7Bi%7D%22);%0A++++++++if+i+%3E+100+%7B%0A++++++++++++break;%0A++++++++%7D%0A++++++++i+*=+2;%0A++++%7D%0A++++assert_eq!(i,+128);%0A%7D&edition=2024 "Run code") Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as expressions that return values via `break`. let mut i = 1; let something = loop { i *= 2; if i > 100 { break i; } }; assert_eq!(something, 128); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+mut+i+=+1;%0A++++let+something+=+loop+%7B%0A++++++++i+*=+2;%0A++++++++if+i+%3E+100+%7B%0A++++++++++++break+i;%0A++++++++%7D%0A++++%7D;%0A++++assert_eq!(something,+128);%0A%7D&edition=2024 "Run code") Every `break` in a loop has to have the same type. When it’s not explicitly giving something, `break;` returns `()`. For more information on `loop` and loops in general, see the [Reference](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html) . See also, [`for`](https://doc.rust-lang.org/stable/std/keyword.for.html) , [`while`](https://doc.rust-lang.org/stable/std/keyword.while.html) . --- # Getting Started - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Let’s start your Rust journey! There’s a lot to learn, but every journey starts somewhere. In this chapter, we’ll discuss: * Installing Rust on Linux, macOS, and Windows * Writing a program that prints `Hello, world!` * Using `cargo`, Rust’s package manager and build system --- # panic in std - Rust [panic](https://doc.rust-lang.org/stable/std/macro.panic.html#) ---------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Macro panic Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/macros.rs.html#14-20) macro_rules! panic { ($($arg:tt)*) => { ... }; } Expand description Panics the current thread. This allows a program to terminate immediately and provide feedback to the caller of the program. This macro is the perfect way to assert conditions in example code and in tests. `panic!` is closely tied with the `unwrap` method of both [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap "method std::option::Option::unwrap") and [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap "method std::result::Result::unwrap") enums. Both implementations call `panic!` when they are set to [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") or [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") variants. When using `panic!()` you can specify a string payload that is built using [formatting syntax](https://doc.rust-lang.org/stable/std/fmt/index.html) . That payload is used when injecting the panic into the calling Rust thread, causing the thread to panic entirely. The behavior of the default `std` hook, i.e. the code that runs directly after the panic is invoked, is to print the message payload to `stderr` along with the file/line/column information of the `panic!()` call. You can override the panic hook using [`std::panic::set_hook()`](https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html) . Inside the hook a panic can be accessed as a `&dyn Any + Send`, which contains either a `&str` or `String` for regular `panic!()` invocations. (Whether a particular invocation contains the payload at type `&str` or `String` is unspecified and can change.) To panic with a value of another other type, [`panic_any`](https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html) can be used. See also the macro [`compile_error!`](https://doc.rust-lang.org/stable/std/macro.compile_error.html "macro std::compile_error") , for raising errors during compilation. [§](https://doc.rust-lang.org/stable/std/macro.panic.html#when-to-use-panic-vs-result) When to use `panic!` vs `Result` ----------------------------------------------------------------------------------------------------------------------- The Rust language provides two complementary systems for constructing / representing, reporting, propagating, reacting to, and discarding errors. These responsibilities are collectively known as “error handling.” `panic!` and `Result` are similar in that they are each the primary interface of their respective error handling systems; however, the meaning these interfaces attach to their errors and the responsibilities they fulfill within their respective error handling systems differ. The `panic!` macro is used to construct errors that represent a bug that has been detected in your program. With `panic!` you provide a message that describes the bug and the language then constructs an error with that message, reports it, and propagates it for you. `Result` on the other hand is used to wrap other types that represent either the successful result of some computation, `Ok(T)`, or error types that represent an anticipated runtime failure mode of that computation, `Err(E)`. `Result` is used alongside user defined types which represent the various anticipated runtime failure modes that the associated computation could encounter. `Result` must be propagated manually, often with the help of the `?` operator and `Try` trait, and they must be reported manually, often with the help of the `Error` trait. For more detailed information about error handling check out the [book](https://doc.rust-lang.org/stable/book/ch09-00-error-handling.html) or the [`std::result`](https://doc.rust-lang.org/stable/std/result/index.html) module docs. [§](https://doc.rust-lang.org/stable/std/macro.panic.html#current-implementation) Current implementation -------------------------------------------------------------------------------------------------------- If the main thread panics it will terminate all your threads and end your program with code `101`. [§](https://doc.rust-lang.org/stable/std/macro.panic.html#editions) Editions ---------------------------------------------------------------------------- Behavior of the panic macros changed over editions. ### [§](https://doc.rust-lang.org/stable/std/macro.panic.html#2021-and-later) 2021 and later In Rust 2021 and later, `panic!` always requires a format string and the applicable format arguments, and is the same in `core` and `std`. Use [`std::panic::panic_any(x)`](https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html) to panic with an arbitrary payload. ### [§](https://doc.rust-lang.org/stable/std/macro.panic.html#2018-and-2015) 2018 and 2015 In Rust Editions prior to 2021, `std::panic!(x)` with a single argument directly uses that argument as a payload. This is true even if the argument is a string literal. For example, `panic!("problem: {reason}")` panics with a payload of literally `"problem: {reason}"` (a `&'static str`). `core::panic!(x)` with a single argument requires that `x` be `&str`, but otherwise behaves like `std::panic!`. In particular, the string need not be a literal, and is not interpreted as a format string. [§](https://doc.rust-lang.org/stable/std/macro.panic.html#examples) Examples ---------------------------------------------------------------------------- [ⓘ](https://doc.rust-lang.org/stable/std/macro.panic.html# "This example panics") panic!(); panic!("this is a terrible mistake!"); panic!("this is a {} {message}", "fancy", message = "message"); std::panic::panic_any(4); // panic with the value of 4 to be collected elsewhere [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unreachable_code)%5D%0A%0Afn+main()+%7B%0A++++panic!();%0A++++panic!(%22this+is+a+terrible+mistake!%22);%0A++++panic!(%22this+is+a+%7B%7D+%7Bmessage%7D%22,+%22fancy%22,+message+=+%22message%22);%0A++++std::panic::panic_any(4);%0A%7D&edition=2024 "Run code") --- # std::ffi - Rust [Module ffi](https://doc.rust-lang.org/stable/std/ffi/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module ffi Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/mod.rs.html#1-207) Expand description Utilities related to FFI bindings. This module provides utilities to handle data across non-Rust interfaces, like other programming languages and the underlying operating system. It is mainly of use for FFI (Foreign Function Interface) bindings and code that needs to exchange C-like strings with other languages. [§](https://doc.rust-lang.org/stable/std/ffi/index.html#overview) Overview -------------------------------------------------------------------------- Rust represents owned strings with the [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") type, and borrowed slices of strings with the [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") primitive. Both are always in UTF-8 encoding, and may contain nul bytes in the middle, i.e., if you look at the bytes that make up the string, there may be a `\0` among them. Both `String` and `str` store their length explicitly; there are no nul terminators at the end of strings like in C. C strings are different from Rust strings: * **Encodings** - Rust strings are UTF-8, but C strings may use other encodings. If you are using a string from C, you should check its encoding explicitly, rather than just assuming that it is UTF-8 like you can do in Rust. * **Character size** - C strings may use `char` or `wchar_t`\-sized characters; please **note** that C’s `char` is different from Rust’s. The C standard leaves the actual sizes of those types open to interpretation, but defines different APIs for strings made up of each character type. Rust strings are always UTF-8, so different Unicode characters will be encoded in a variable number of bytes each. The Rust type [`char`](https://doc.rust-lang.org/stable/std/primitive.char.html "primitive char") represents a ‘[Unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value) ’, which is similar to, but not the same as, a ‘[Unicode code point](https://www.unicode.org/glossary/#code_point) ’. * **Nul terminators and implicit string lengths** - Often, C strings are nul-terminated, i.e., they have a `\0` character at the end. The length of a string buffer is not stored, but has to be calculated; to compute the length of a string, C code must manually call a function like `strlen()` for `char`\-based strings, or `wcslen()` for `wchar_t`\-based ones. Those functions return the number of characters in the string excluding the nul terminator, so the buffer length is really `len+1` characters. Rust strings don’t have a nul terminator; their length is always stored and does not need to be calculated. While in Rust accessing a string’s length is an _O_(1) operation (because the length is stored); in C it is an _O_(_n_) operation because the length needs to be computed by scanning the string for the nul terminator. * **Internal nul characters** - When C strings have a nul terminator character, this usually means that they cannot have nul characters in the middle — a nul character would essentially truncate the string. Rust strings _can_ have nul characters in the middle, because nul does not have to mark the end of the string in Rust. [§](https://doc.rust-lang.org/stable/std/ffi/index.html#representations-of-non-rust-strings) Representations of non-Rust strings -------------------------------------------------------------------------------------------------------------------------------- [`CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") and [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") are useful when you need to transfer UTF-8 strings to and from languages with a C ABI, like Python. * **From Rust to C:** [`CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") represents an owned, C-friendly string: it is nul-terminated, and has no internal nul characters. Rust code can create a [`CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") out of a normal string (provided that the string doesn’t have nul characters in the middle), and then use a variety of methods to obtain a raw `*mut [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") ` that can then be passed as an argument to functions which use the C conventions for strings. * **From C to Rust:** [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") represents a borrowed C string; it is what you would use to wrap a raw `*const [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") ` that you got from a C function. A [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") is guaranteed to be a nul-terminated array of bytes. Once you have a [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") , you can convert it to a Rust `&[str](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") ` if it’s valid UTF-8, or lossily convert it by adding replacement characters. [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") and [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") are useful when you need to transfer strings to and from the operating system itself, or when capturing the output of external commands. Conversions between [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") , [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") and Rust strings work similarly to those for [`CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") and [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") . * [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") losslessly represents an owned platform string. However, this representation is not necessarily in a form native to the platform. In the Rust standard library, various APIs that transfer strings to/from the operating system use [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") instead of plain strings. For example, [`env::var_os()`](https://doc.rust-lang.org/stable/std/env/fn.var_os.html "env::var_os") is used to query environment variables; it returns an `[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") >`. If the environment variable exists you will get a `[Some](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.Some "variant std::option::Option::Some") (os_string)`, which you can _then_ try to convert to a Rust string. This yields a [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") , so that your code can detect errors in case the environment variable did not in fact contain valid Unicode data. * [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") losslessly represents a borrowed reference to a platform string. However, this representation is not necessarily in a form native to the platform. It can be converted into a UTF-8 Rust string slice in a similar way to [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") . [§](https://doc.rust-lang.org/stable/std/ffi/index.html#conversions) Conversions -------------------------------------------------------------------------------- ### [§](https://doc.rust-lang.org/stable/std/ffi/index.html#on-unix) On Unix On Unix, [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") implements the `std::os::unix::ffi::[OsStrExt](https://doc.rust-lang.org/stable/std/os/unix/ffi/trait.OsStrExt.html "os::unix::ffi::OsStrExt") ` trait, which augments it with two methods, [`from_bytes`](https://doc.rust-lang.org/stable/std/os/unix/ffi/trait.OsStrExt.html#tymethod.from_bytes "os::unix::ffi::OsStrExt::from_bytes") and [`as_bytes`](https://doc.rust-lang.org/stable/std/os/unix/ffi/trait.OsStrExt.html#tymethod.as_bytes "os::unix::ffi::OsStrExt::as_bytes") . These do inexpensive conversions from and to byte slices. Additionally, on Unix [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") implements the `std::os::unix::ffi::[OsStringExt](https://doc.rust-lang.org/stable/std/os/unix/ffi/trait.OsStringExt.html "os::unix::ffi::OsStringExt") ` trait, which provides [`from_vec`](https://doc.rust-lang.org/stable/std/os/unix/ffi/trait.OsStringExt.html#tymethod.from_vec "os::unix::ffi::OsStringExt::from_vec") and [`into_vec`](https://doc.rust-lang.org/stable/std/os/unix/ffi/trait.OsStringExt.html#tymethod.into_vec "os::unix::ffi::OsStringExt::into_vec") methods that consume their arguments, and take or produce vectors of [`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") . ### [§](https://doc.rust-lang.org/stable/std/ffi/index.html#on-windows) On Windows An [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") can be losslessly converted to a native Windows string. And a native Windows string can be losslessly converted to an [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") . On Windows, [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") implements the `std::os::windows::ffi::[OsStrExt](https://doc.rust-lang.org/stable/std/os/windows/ffi/trait.OsStrExt.html "os::windows::ffi::OsStrExt") ` trait, which provides an [`encode_wide`](https://doc.rust-lang.org/stable/std/os/windows/ffi/trait.OsStrExt.html#tymethod.encode_wide "os::windows::ffi::OsStrExt::encode_wide") method. This provides an iterator that can be [`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect "iter::Iterator::collect") ed into a vector of [`u16`](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive u16") . After a nul characters is appended, this is the same as a native Windows string. Additionally, on Windows [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") implements the `std::os::windows:ffi::[OsStringExt](https://doc.rust-lang.org/stable/std/os/windows/ffi/trait.OsStringExt.html "os::windows::ffi::OsStringExt") ` trait, which provides a [`from_wide`](https://doc.rust-lang.org/stable/std/os/windows/ffi/trait.OsStringExt.html#tymethod.from_wide "os::windows::ffi::OsStringExt::from_wide") method to convert a native Windows string (without the terminating nul character) to an [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") . ### [§](https://doc.rust-lang.org/stable/std/ffi/index.html#other-platforms) Other platforms Many other platforms provide their own extension traits in a `std::os::*::ffi` module. ### [§](https://doc.rust-lang.org/stable/std/ffi/index.html#on-all-platforms) On all platforms On all platforms, [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") consists of a sequence of bytes that is encoded as a superset of UTF-8; see [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") for more details on its encoding on different platforms. For limited, inexpensive conversions from and to bytes, see [`OsStr::as_encoded_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.as_encoded_bytes "method std::ffi::OsStr::as_encoded_bytes") and [`OsStr::from_encoded_bytes_unchecked`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.from_encoded_bytes_unchecked "associated function std::ffi::OsStr::from_encoded_bytes_unchecked") . For basic string processing, see [`OsStr::slice_encoded_bytes`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html#method.slice_encoded_bytes "method std::ffi::OsStr::slice_encoded_bytes") . Modules[§](https://doc.rust-lang.org/stable/std/ffi/index.html#modules) ------------------------------------------------------------------------ [c\_str](https://doc.rust-lang.org/stable/std/ffi/c_str/index.html "mod std::ffi::c_str") [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") , [`CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") , and related types. [os\_str](https://doc.rust-lang.org/stable/std/ffi/os_str/index.html "mod std::ffi::os_str") The [`OsStr`](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") and [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") types and associated utilities. Structs[§](https://doc.rust-lang.org/stable/std/ffi/index.html#structs) ------------------------------------------------------------------------ [CStr](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") Representation of a borrowed C string. [CString](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the middle. [FromBytesUntilNulError](https://doc.rust-lang.org/stable/std/ffi/struct.FromBytesUntilNulError.html "struct std::ffi::FromBytesUntilNulError") An error indicating that no nul byte was present. [FromVecWithNulError](https://doc.rust-lang.org/stable/std/ffi/struct.FromVecWithNulError.html "struct std::ffi::FromVecWithNulError") An error indicating that a nul byte was not in the expected position. [IntoStringError](https://doc.rust-lang.org/stable/std/ffi/struct.IntoStringError.html "struct std::ffi::IntoStringError") An error indicating invalid UTF-8 when converting a [`CString`](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") into a [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") . [NulError](https://doc.rust-lang.org/stable/std/ffi/struct.NulError.html "struct std::ffi::NulError") An error indicating that an interior nul byte was found. [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") Borrowed reference to an OS string (see [`OsString`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") ). [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") A type that can represent owned, mutable platform-native strings, but is cheaply inter-convertible with Rust strings. [VaList](https://doc.rust-lang.org/stable/std/ffi/struct.VaList.html "struct std::ffi::VaList") Experimental A wrapper for a `va_list` [VaListImpl](https://doc.rust-lang.org/stable/std/ffi/struct.VaListImpl.html "struct std::ffi::VaListImpl") Experimental x86\_64 ABI implementation of a `va_list`. Enums[§](https://doc.rust-lang.org/stable/std/ffi/index.html#enums) -------------------------------------------------------------------- [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") An error indicating that a nul byte was not in the expected position. [c\_void](https://doc.rust-lang.org/stable/std/ffi/enum.c_void.html "enum std::ffi::c_void") Equivalent to C’s `void` type when used as a [pointer](https://doc.rust-lang.org/stable/std/primitive.pointer.html "primitive pointer") . Traits[§](https://doc.rust-lang.org/stable/std/ffi/index.html#traits) ---------------------------------------------------------------------- [VaArgSafe](https://doc.rust-lang.org/stable/std/ffi/trait.VaArgSafe.html "trait std::ffi::VaArgSafe") Experimental Types that are valid to read using [`VaListImpl::arg`](https://doc.rust-lang.org/stable/std/ffi/struct.VaListImpl.html#method.arg "method std::ffi::VaListImpl::arg") . Type Aliases[§](https://doc.rust-lang.org/stable/std/ffi/index.html#types) --------------------------------------------------------------------------- [c\_char](https://doc.rust-lang.org/stable/std/ffi/type.c_char.html "type std::ffi::c_char") Equivalent to C’s `char` type. [c\_double](https://doc.rust-lang.org/stable/std/ffi/type.c_double.html "type std::ffi::c_double") Equivalent to C’s `double` type. [c\_float](https://doc.rust-lang.org/stable/std/ffi/type.c_float.html "type std::ffi::c_float") Equivalent to C’s `float` type. [c\_int](https://doc.rust-lang.org/stable/std/ffi/type.c_int.html "type std::ffi::c_int") Equivalent to C’s `signed int` (`int`) type. [c\_long](https://doc.rust-lang.org/stable/std/ffi/type.c_long.html "type std::ffi::c_long") Equivalent to C’s `signed long` (`long`) type. [c\_longlong](https://doc.rust-lang.org/stable/std/ffi/type.c_longlong.html "type std::ffi::c_longlong") Equivalent to C’s `signed long long` (`long long`) type. [c\_schar](https://doc.rust-lang.org/stable/std/ffi/type.c_schar.html "type std::ffi::c_schar") Equivalent to C’s `signed char` type. [c\_short](https://doc.rust-lang.org/stable/std/ffi/type.c_short.html "type std::ffi::c_short") Equivalent to C’s `signed short` (`short`) type. [c\_uchar](https://doc.rust-lang.org/stable/std/ffi/type.c_uchar.html "type std::ffi::c_uchar") Equivalent to C’s `unsigned char` type. [c\_uint](https://doc.rust-lang.org/stable/std/ffi/type.c_uint.html "type std::ffi::c_uint") Equivalent to C’s `unsigned int` type. [c\_ulong](https://doc.rust-lang.org/stable/std/ffi/type.c_ulong.html "type std::ffi::c_ulong") Equivalent to C’s `unsigned long` type. [c\_ulonglong](https://doc.rust-lang.org/stable/std/ffi/type.c_ulonglong.html "type std::ffi::c_ulonglong") Equivalent to C’s `unsigned long long` type. [c\_ushort](https://doc.rust-lang.org/stable/std/ffi/type.c_ushort.html "type std::ffi::c_ushort") Equivalent to C’s `unsigned short` type. [c\_ptrdiff\_t](https://doc.rust-lang.org/stable/std/ffi/type.c_ptrdiff_t.html "type std::ffi::c_ptrdiff_t") Experimental Equivalent to C’s `ptrdiff_t` type, from `stddef.h` (or `cstddef` for C++). [c\_size\_t](https://doc.rust-lang.org/stable/std/ffi/type.c_size_t.html "type std::ffi::c_size_t") Experimental Equivalent to C’s `size_t` type, from `stddef.h` (or `cstddef` for C++). [c\_ssize\_t](https://doc.rust-lang.org/stable/std/ffi/type.c_ssize_t.html "type std::ffi::c_ssize_t") Experimental Equivalent to C’s `ssize_t` (on POSIX) or `SSIZE_T` (on Windows) type. --- # Programming a Guessing Game - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about `let`, `match`, methods, associated functions, external crates, and more! In the following chapters, we’ll explore these ideas in more detail. In this chapter, you’ll just practice the fundamentals. We’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: The program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit. To set up a new project, go to the _projects_ directory that you created in Chapter 1 and make a new project using Cargo, like so: $ cargo new guessing_game $ cd guessing_game The first command, `cargo new`, takes the name of the project (`guessing_game`) as the first argument. The second command changes to the new project’s directory. Look at the generated _Cargo.toml_ file: Filename: Cargo.toml [package] name = "guessing_game" version = "0.1.0" edition = "2024" [dependencies] As you saw in Chapter 1, `cargo new` generates a “Hello, world!” program for you. Check out the _src/main.rs_ file: Filename: src/main.rs fn main() { println!("Hello, world!"); } Now let’s compile this “Hello, world!” program and run it in the same step using the `cargo run` command: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s Running `target/debug/guessing_game` Hello, world! The `run` command comes in handy when you need to rapidly iterate on a project, as we’ll do in this game, quickly testing each iteration before moving on to the next one. Reopen the _src/main.rs_ file. You’ll be writing all the code in this file. The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess. Enter the code in Listing 2-1 into _src/main.rs_. Filename: src/main.rs use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } [Listing 2-1](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#listing-2-1) : Code that gets a guess from the user and prints it This code contains a lot of information, so let’s go over it line by line. To obtain user input and then print the result as output, we need to bring the `io` input/output library into scope. The `io` library comes from the standard library, known as `std`: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the _prelude_, and you can see everything in it [in the standard library documentation](https://doc.rust-lang.org/stable/std/prelude/index.html) . If a type you want to use isn’t in the prelude, you have to bring that type into scope explicitly with a `use` statement. Using the `std::io` library provides you with a number of useful features, including the ability to accept user input. As you saw in Chapter 1, the `main` function is the entry point into the program: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } The `fn` syntax declares a new function; the parentheses, `()`, indicate there are no parameters; and the curly bracket, `{`, starts the body of the function. As you also learned in Chapter 1, `println!` is a macro that prints a string to the screen: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } This code is printing a prompt stating what the game is and requesting input from the user. Next, we’ll create a _variable_ to store the user input, like this: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } Now the program is getting interesting! There’s a lot going on in this little line. We use the `let` statement to create the variable. Here’s another example: let apples = 5; This line creates a new variable named `apples` and binds it to the value `5`. In Rust, variables are immutable by default, meaning once we give the variable a value, the value won’t change. We’ll be discussing this concept in detail in the [“Variables and Mutability”](https://doc.rust-lang.org/stable/book/ch03-01-variables-and-mutability.html#variables-and-mutability) section in Chapter 3. To make a variable mutable, we add `mut` before the variable name: let apples = 5; // immutable let mut bananas = 5; // mutable Note: The `//` syntax starts a comment that continues until the end of the line. Rust ignores everything in comments. We’ll discuss comments in more detail in [Chapter 3](https://doc.rust-lang.org/stable/book/ch03-04-comments.html) . Returning to the guessing game program, you now know that `let mut guess` will introduce a mutable variable named `guess`. The equal sign (`=`) tells Rust we want to bind something to the variable now. On the right of the equal sign is the value that `guess` is bound to, which is the result of calling `String::new`, a function that returns a new instance of a `String`. [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html) is a string type provided by the standard library that is a growable, UTF-8 encoded bit of text. The `::` syntax in the `::new` line indicates that `new` is an associated function of the `String` type. An _associated function_ is a function that’s implemented on a type, in this case `String`. This `new` function creates a new, empty string. You’ll find a `new` function on many types because it’s a common name for a function that makes a new value of some kind. In full, the `let mut guess = String::new();` line has created a mutable variable that is currently bound to a new, empty instance of a `String`. Whew! Recall that we included the input/output functionality from the standard library with `use std::io;` on the first line of the program. Now we’ll call the `stdin` function from the `io` module, which will allow us to handle user input: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } If we hadn’t imported the `io` module with `use std::io;` at the beginning of the program, we could still use the function by writing this function call as `std::io::stdin`. The `stdin` function returns an instance of [`std::io::Stdin`](https://doc.rust-lang.org/stable/std/io/struct.Stdin.html) , which is a type that represents a handle to the standard input for your terminal. Next, the line `.read_line(&mut guess)` calls the [`read_line`](https://doc.rust-lang.org/stable/std/io/struct.Stdin.html#method.read_line) method on the standard input handle to get input from the user. We’re also passing `&mut guess` as the argument to `read_line` to tell it what string to store the user input in. The full job of `read_line` is to take whatever the user types into standard input and append that into a string (without overwriting its contents), so we therefore pass that string as an argument. The string argument needs to be mutable so that the method can change the string’s content. The `&` indicates that this argument is a _reference_, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times. References are a complex feature, and one of Rust’s major advantages is how safe and easy it is to use references. You don’t need to know a lot of those details to finish this program. For now, all you need to know is that, like variables, references are immutable by default. Hence, you need to write `&mut guess` rather than `&guess` to make it mutable. (Chapter 4 will explain references more thoroughly.) We’re still working on this line of code. We’re now discussing a third line of text, but note that it’s still part of a single logical line of code. The next part is this method: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } We could have written this code as: io::stdin().read_line(&mut guess).expect("Failed to read line"); However, one long line is difficult to read, so it’s best to divide it. It’s often wise to introduce a newline and other whitespace to help break up long lines when you call a method with the `.method_name()` syntax. Now let’s discuss what this line does. As mentioned earlier, `read_line` puts whatever the user enters into the string we pass to it, but it also returns a `Result` value. [`Result`](https://doc.rust-lang.org/stable/std/result/enum.Result.html) is an [_enumeration_](https://doc.rust-lang.org/stable/book/ch06-00-enums.html) , often called an _enum_, which is a type that can be in one of multiple possible states. We call each possible state a _variant_. [Chapter 6](https://doc.rust-lang.org/stable/book/ch06-00-enums.html) will cover enums in more detail. The purpose of these `Result` types is to encode error-handling information. `Result`’s variants are `Ok` and `Err`. The `Ok` variant indicates the operation was successful, and it contains the successfully generated value. The `Err` variant means the operation failed, and it contains information about how or why the operation failed. Values of the `Result` type, like values of any type, have methods defined on them. An instance of `Result` has an [`expect` method](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.expect) that you can call. If this instance of `Result` is an `Err` value, `expect` will cause the program to crash and display the message that you passed as an argument to `expect`. If the `read_line` method returns an `Err`, it would likely be the result of an error coming from the underlying operating system. If this instance of `Result` is an `Ok` value, `expect` will take the return value that `Ok` is holding and return just that value to you so that you can use it. In this case, that value is the number of bytes in the user’s input. If you don’t call `expect`, the program will compile, but you’ll get a warning: $ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) warning: unused `Result` that must be used --> src/main.rs:10:5 | 10 | io::stdin().read_line(&mut guess); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this `Result` may be an `Err` variant, which should be handled = note: `#[warn(unused_must_use)]` on by default help: use `let _ = ...` to ignore the resulting value | 10 | let _ = io::stdin().read_line(&mut guess); | +++++++ warning: `guessing_game` (bin "guessing_game") generated 1 warning Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.59s Rust warns that you haven’t used the `Result` value returned from `read_line`, indicating that the program hasn’t handled a possible error. The right way to suppress the warning is to actually write error-handling code, but in our case we just want to crash this program when a problem occurs, so we can use `expect`. You’ll learn about recovering from errors in [Chapter 9](https://doc.rust-lang.org/stable/book/ch09-02-recoverable-errors-with-result.html) . Aside from the closing curly bracket, there’s only one more line to discuss in the code so far: use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } This line prints the string that now contains the user’s input. The `{}` set of curly brackets is a placeholder: Think of `{}` as little crab pincers that hold a value in place. When printing the value of a variable, the variable name can go inside the curly brackets. When printing the result of evaluating an expression, place empty curly brackets in the format string, then follow the format string with a comma-separated list of expressions to print in each empty curly bracket placeholder in the same order. Printing a variable and the result of an expression in one call to `println!` would look like this: #![allow(unused)] fn main() { let x = 5; let y = 10; println!("x = {x} and y + 2 = {}", y + 2); } This code would print `x = 5 and y + 2 = 12`. Let’s test the first part of the guessing game. Run it using `cargo run`: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.44s Running `target/debug/guessing_game` Guess the number! Please input your guess. 6 You guessed: 6 At this point, the first part of the game is done: We’re getting input from the keyboard and then printing it. Next, we need to generate a secret number that the user will try to guess. The secret number should be different every time so that the game is fun to play more than once. We’ll use a random number between 1 and 100 so that the game isn’t too difficult. Rust doesn’t yet include random number functionality in its standard library. However, the Rust team does provide a [`rand` crate](https://crates.io/crates/rand) with said functionality. Remember that a crate is a collection of Rust source code files. The project we’ve been building is a binary crate, which is an executable. The `rand` crate is a library crate, which contains code that is intended to be used in other programs and can’t be executed on its own. Cargo’s coordination of external crates is where Cargo really shines. Before we can write code that uses `rand`, we need to modify the _Cargo.toml_ file to include the `rand` crate as a dependency. Open that file now and add the following line to the bottom, beneath the `[dependencies]` section header that Cargo created for you. Be sure to specify `rand` exactly as we have here, with this version number, or the code examples in this tutorial may not work: Filename: Cargo.toml [dependencies] rand = "0.8.5" In the _Cargo.toml_ file, everything that follows a header is part of that section that continues until another section starts. In `[dependencies]`, you tell Cargo which external crates your project depends on and which versions of those crates you require. In this case, we specify the `rand` crate with the semantic version specifier `0.8.5`. Cargo understands [Semantic Versioning](http://semver.org/) (sometimes called _SemVer_), which is a standard for writing version numbers. The specifier `0.8.5` is actually shorthand for `^0.8.5`, which means any version that is at least 0.8.5 but below 0.9.0. Cargo considers these versions to have public APIs compatible with version 0.8.5, and this specification ensures that you’ll get the latest patch release that will still compile with the code in this chapter. Any version 0.9.0 or greater is not guaranteed to have the same API as what the following examples use. Now, without changing any of the code, let’s build the project, as shown in Listing 2-2. $ cargo build Updating crates.io index Locking 15 packages to latest Rust 1.85.0 compatible versions Adding rand v0.8.5 (available: v0.9.0) Compiling proc-macro2 v1.0.93 Compiling unicode-ident v1.0.17 Compiling libc v0.2.170 Compiling cfg-if v1.0.0 Compiling byteorder v1.5.0 Compiling getrandom v0.2.15 Compiling rand_core v0.6.4 Compiling quote v1.0.38 Compiling syn v2.0.98 Compiling zerocopy-derive v0.7.35 Compiling zerocopy v0.7.35 Compiling ppv-lite86 v0.2.20 Compiling rand_chacha v0.3.1 Compiling rand v0.8.5 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.48s [Listing 2-2](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#listing-2-2) : The output from running `cargo build` after adding the `rand` crate as a dependency You may see different version numbers (but they will all be compatible with the code, thanks to SemVer!) and different lines (depending on the operating system), and the lines may be in a different order. When we include an external dependency, Cargo fetches the latest versions of everything that dependency needs from the _registry_, which is a copy of data from [Crates.io](https://crates.io/) . Crates.io is where people in the Rust ecosystem post their open source Rust projects for others to use. After updating the registry, Cargo checks the `[dependencies]` section and downloads any crates listed that aren’t already downloaded. In this case, although we only listed `rand` as a dependency, Cargo also grabbed other crates that `rand` depends on to work. After downloading the crates, Rust compiles them and then compiles the project with the dependencies available. If you immediately run `cargo build` again without making any changes, you won’t get any output aside from the `Finished` line. Cargo knows it has already downloaded and compiled the dependencies, and you haven’t changed anything about them in your _Cargo.toml_ file. Cargo also knows that you haven’t changed anything about your code, so it doesn’t recompile that either. With nothing to do, it simply exits. If you open the _src/main.rs_ file, make a trivial change, and then save it and build again, you’ll only see two lines of output: $ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s These lines show that Cargo only updates the build with your tiny change to the _src/main.rs_ file. Your dependencies haven’t changed, so Cargo knows it can reuse what it has already downloaded and compiled for those. Cargo has a mechanism that ensures that you can rebuild the same artifact every time you or anyone else builds your code: Cargo will use only the versions of the dependencies you specified until you indicate otherwise. For example, say that next week version 0.8.6 of the `rand` crate comes out, and that version contains an important bug fix, but it also contains a regression that will break your code. To handle this, Rust creates the _Cargo.lock_ file the first time you run `cargo build`, so we now have this in the _guessing\_game_ directory. When you build a project for the first time, Cargo figures out all the versions of the dependencies that fit the criteria and then writes them to the _Cargo.lock_ file. When you build your project in the future, Cargo will see that the _Cargo.lock_ file exists and will use the versions specified there rather than doing all the work of figuring out versions again. This lets you have a reproducible build automatically. In other words, your project will remain at 0.8.5 until you explicitly upgrade, thanks to the _Cargo.lock_ file. Because the _Cargo.lock_ file is important for reproducible builds, it’s often checked into source control with the rest of the code in your project. When you _do_ want to update a crate, Cargo provides the command `update`, which will ignore the _Cargo.lock_ file and figure out all the latest versions that fit your specifications in _Cargo.toml_. Cargo will then write those versions to the _Cargo.lock_ file. Otherwise, by default, Cargo will only look for versions greater than 0.8.5 and less than 0.9.0. If the `rand` crate has released the two new versions 0.8.6 and 0.9.0, you would see the following if you ran `cargo update`: $ cargo update Updating crates.io index Locking 1 package to latest Rust 1.85.0 compatible version Updating rand v0.8.5 -> v0.8.6 (available: v0.9.0) Cargo ignores the 0.9.0 release. At this point, you would also notice a change in your _Cargo.lock_ file noting that the version of the `rand` crate you are now using is 0.8.6. To use `rand` version 0.9.0 or any version in the 0.9._x_ series, you’d have to update the _Cargo.toml_ file to look like this instead: [dependencies] rand = "0.9.0" The next time you run `cargo build`, Cargo will update the registry of crates available and reevaluate your `rand` requirements according to the new version you have specified. There’s a lot more to say about [Cargo](https://doc.rust-lang.org/cargo/) and [its ecosystem](https://doc.rust-lang.org/cargo/reference/publishing.html) , which we’ll discuss in Chapter 14, but for now, that’s all you need to know. Cargo makes it very easy to reuse libraries, so Rustaceans are able to write smaller projects that are assembled from a number of packages. Let’s start using `rand` to generate a number to guess. The next step is to update _src/main.rs_, as shown in Listing 2-3. Filename: src/main.rs use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } [Listing 2-3](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#listing-2-3) : Adding code to generate a random number First, we add the line `use rand::Rng;`. The `Rng` trait defines methods that random number generators implement, and this trait must be in scope for us to use those methods. Chapter 10 will cover traits in detail. Next, we’re adding two lines in the middle. In the first line, we call the `rand::thread_rng` function that gives us the particular random number generator we’re going to use: one that is local to the current thread of execution and is seeded by the operating system. Then, we call the `gen_range` method on the random number generator. This method is defined by the `Rng` trait that we brought into scope with the `use rand::Rng;` statement. The `gen_range` method takes a range expression as an argument and generates a random number in the range. The kind of range expression we’re using here takes the form `start..=end` and is inclusive on the lower and upper bounds, so we need to specify `1..=100` to request a number between 1 and 100. Note: You won’t just know which traits to use and which methods and functions to call from a crate, so each crate has documentation with instructions for using it. Another neat feature of Cargo is that running the `cargo doc --open` command will build documentation provided by all your dependencies locally and open it in your browser. If you’re interested in other functionality in the `rand` crate, for example, run `cargo doc --open` and click `rand` in the sidebar on the left. The second new line prints the secret number. This is useful while we’re developing the program to be able to test it, but we’ll delete it from the final version. It’s not much of a game if the program prints the answer as soon as it starts! Try running the program a few times: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s Running `target/debug/guessing_game` Guess the number! The secret number is: 7 Please input your guess. 4 You guessed: 4 $ cargo run Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s Running `target/debug/guessing_game` Guess the number! The secret number is: 83 Please input your guess. 5 You guessed: 5 You should get different random numbers, and they should all be numbers between 1 and 100. Great job! Now that we have user input and a random number, we can compare them. That step is shown in Listing 2-4. Note that this code won’t compile just yet, as we will explain. Filename: src/main.rs use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { // --snip-- println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } [Listing 2-4](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#listing-2-4) : Handling the possible return values of comparing two numbers First, we add another `use` statement, bringing a type called `std::cmp::Ordering` into scope from the standard library. The `Ordering` type is another enum and has the variants `Less`, `Greater`, and `Equal`. These are the three outcomes that are possible when you compare two values. Then, we add five new lines at the bottom that use the `Ordering` type. The `cmp` method compares two values and can be called on anything that can be compared. It takes a reference to whatever you want to compare with: Here, it’s comparing `guess` to `secret_number`. Then, it returns a variant of the `Ordering` enum we brought into scope with the `use` statement. We use a [`match`](https://doc.rust-lang.org/stable/book/ch06-02-match.html) expression to decide what to do next based on which variant of `Ordering` was returned from the call to `cmp` with the values in `guess` and `secret_number`. A `match` expression is made up of _arms_. An arm consists of a _pattern_ to match against, and the code that should be run if the value given to `match` fits that arm’s pattern. Rust takes the value given to `match` and looks through each arm’s pattern in turn. Patterns and the `match` construct are powerful Rust features: They let you express a variety of situations your code might encounter, and they make sure you handle them all. These features will be covered in detail in Chapter 6 and Chapter 19, respectively. Let’s walk through an example with the `match` expression we use here. Say that the user has guessed 50 and the randomly generated secret number this time is 38. When the code compares 50 to 38, the `cmp` method will return `Ordering::Greater` because 50 is greater than 38. The `match` expression gets the `Ordering::Greater` value and starts checking each arm’s pattern. It looks at the first arm’s pattern, `Ordering::Less`, and sees that the value `Ordering::Greater` does not match `Ordering::Less`, so it ignores the code in that arm and moves to the next arm. The next arm’s pattern is `Ordering::Greater`, which _does_ match `Ordering::Greater`! The associated code in that arm will execute and print `Too big!` to the screen. The `match` expression ends after the first successful match, so it won’t look at the last arm in this scenario. However, the code in Listing 2-4 won’t compile yet. Let’s try it: $ cargo build Compiling libc v0.2.86 Compiling getrandom v0.2.2 Compiling cfg-if v1.0.0 Compiling ppv-lite86 v0.2.10 Compiling rand_core v0.6.2 Compiling rand_chacha v0.3.0 Compiling rand v0.8.5 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) error[E0308]: mismatched types --> src/main.rs:23:21 | 23 | match guess.cmp(&secret_number) { | --- ^^^^^^^^^^^^^^ expected `&String`, found `&{integer}` | | | arguments to this method are incorrect | = note: expected reference `&String` found reference `&{integer}` note: method defined here --> /rustc/4eb161250e340c8f48f66e2b929ef4a5bed7c181/library/core/src/cmp.rs:964:8 For more information about this error, try `rustc --explain E0308`. error: could not compile `guessing_game` (bin "guessing_game") due to 1 previous error The core of the error states that there are _mismatched types_. Rust has a strong, static type system. However, it also has type inference. When we wrote `let mut guess = String::new()`, Rust was able to infer that `guess` should be a `String` and didn’t make us write the type. The `secret_number`, on the other hand, is a number type. A few of Rust’s number types can have a value between 1 and 100: `i32`, a 32-bit number; `u32`, an unsigned 32-bit number; `i64`, a 64-bit number; as well as others. Unless otherwise specified, Rust defaults to an `i32`, which is the type of `secret_number` unless you add type information elsewhere that would cause Rust to infer a different numerical type. The reason for the error is that Rust cannot compare a string and a number type. Ultimately, we want to convert the `String` the program reads as input into a number type so that we can compare it numerically to the secret number. We do so by adding this line to the `main` function body: Filename: src/main.rs use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); // --snip-- let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } The line is: let guess: u32 = guess.trim().parse().expect("Please type a number!"); We create a variable named `guess`. But wait, doesn’t the program already have a variable named `guess`? It does, but helpfully Rust allows us to shadow the previous value of `guess` with a new one. _Shadowing_ lets us reuse the `guess` variable name rather than forcing us to create two unique variables, such as `guess_str` and `guess`, for example. We’ll cover this in more detail in [Chapter 3](https://doc.rust-lang.org/stable/book/ch03-01-variables-and-mutability.html#shadowing) , but for now, know that this feature is often used when you want to convert a value from one type to another type. We bind this new variable to the expression `guess.trim().parse()`. The `guess` in the expression refers to the original `guess` variable that contained the input as a string. The `trim` method on a `String` instance will eliminate any whitespace at the beginning and end, which we must do before we can convert the string to a `u32`, which can only contain numerical data. The user must press enter to satisfy `read_line` and input their guess, which adds a newline character to the string. For example, if the user types 5 and presses enter, `guess` looks like this: `5\n`. The `\n` represents “newline.” (On Windows, pressing enter results in a carriage return and a newline, `\r\n`.) The `trim` method eliminates `\n` or `\r\n`, resulting in just `5`. The [`parse` method on strings](https://doc.rust-lang.org/stable/std/primitive.str.html#method.parse) converts a string to another type. Here, we use it to convert from a string to a number. We need to tell Rust the exact number type we want by using `let guess: u32`. The colon (`:`) after `guess` tells Rust we’ll annotate the variable’s type. Rust has a few built-in number types; the `u32` seen here is an unsigned, 32-bit integer. It’s a good default choice for a small positive number. You’ll learn about other number types in [Chapter 3](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html#integer-types) . Additionally, the `u32` annotation in this example program and the comparison with `secret_number` means Rust will infer that `secret_number` should be a `u32` as well. So, now the comparison will be between two values of the same type! The `parse` method will only work on characters that can logically be converted into numbers and so can easily cause errors. If, for example, the string contained `A👍%`, there would be no way to convert that to a number. Because it might fail, the `parse` method returns a `Result` type, much as the `read_line` method does (discussed earlier in [“Handling Potential Failure with `Result`”](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-result) ). We’ll treat this `Result` the same way by using the `expect` method again. If `parse` returns an `Err` `Result` variant because it couldn’t create a number from the string, the `expect` call will crash the game and print the message we give it. If `parse` can successfully convert the string to a number, it will return the `Ok` variant of `Result`, and `expect` will return the number that we want from the `Ok` value. Let’s run the program now: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.26s Running `target/debug/guessing_game` Guess the number! The secret number is: 58 Please input your guess. 76 You guessed: 76 Too big! Nice! Even though spaces were added before the guess, the program still figured out that the user guessed 76. Run the program a few times to verify the different behavior with different kinds of input: Guess the number correctly, guess a number that is too high, and guess a number that is too low. We have most of the game working now, but the user can make only one guess. Let’s change that by adding a loop! The `loop` keyword creates an infinite loop. We’ll add a loop to give users more chances at guessing the number: Filename: src/main.rs use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); // --snip-- println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); // --snip-- let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } } As you can see, we’ve moved everything from the guess input prompt onward into a loop. Be sure to indent the lines inside the loop another four spaces each and run the program again. The program will now ask for another guess forever, which actually introduces a new problem. It doesn’t seem like the user can quit! The user could always interrupt the program by using the keyboard shortcut ctrl\-C. But there’s another way to escape this insatiable monster, as mentioned in the `parse` discussion in [“Comparing the Guess to the Secret Number”](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number) : If the user enters a non-number answer, the program will crash. We can take advantage of that to allow the user to quit, as shown here: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.23s Running `target/debug/guessing_game` Guess the number! The secret number is: 59 Please input your guess. 45 You guessed: 45 Too small! Please input your guess. 60 You guessed: 60 Too big! Please input your guess. 59 You guessed: 59 You win! Please input your guess. quit thread 'main' panicked at src/main.rs:28:47: Please type a number!: ParseIntError { kind: InvalidDigit } note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Typing `quit` will quit the game, but as you’ll notice, so will entering any other non-number input. This is suboptimal, to say the least; we want the game to also stop when the correct number is guessed. Let’s program the game to quit when the user wins by adding a `break` statement: Filename: src/main.rs use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); // --snip-- match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } Adding the `break` line after `You win!` makes the program exit the loop when the user guesses the secret number correctly. Exiting the loop also means exiting the program, because the loop is the last part of `main`. To further refine the game’s behavior, rather than crashing the program when the user inputs a non-number, let’s make the game ignore a non-number so that the user can continue guessing. We can do that by altering the line where `guess` is converted from a `String` to a `u32`, as shown in Listing 2-5. Filename: src/main.rs use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); let mut guess = String::new(); // --snip-- io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {guess}"); // --snip-- match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } [Listing 2-5](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#listing-2-5) : Ignoring a non-number guess and asking for another guess instead of crashing the program We switch from an `expect` call to a `match` expression to move from crashing on an error to handling the error. Remember that `parse` returns a `Result` type and `Result` is an enum that has the variants `Ok` and `Err`. We’re using a `match` expression here, as we did with the `Ordering` result of the `cmp` method. If `parse` is able to successfully turn the string into a number, it will return an `Ok` value that contains the resultant number. That `Ok` value will match the first arm’s pattern, and the `match` expression will just return the `num` value that `parse` produced and put inside the `Ok` value. That number will end up right where we want it in the new `guess` variable we’re creating. If `parse` is _not_ able to turn the string into a number, it will return an `Err` value that contains more information about the error. The `Err` value does not match the `Ok(num)` pattern in the first `match` arm, but it does match the `Err(_)` pattern in the second arm. The underscore, `_`, is a catch-all value; in this example, we’re saying we want to match all `Err` values, no matter what information they have inside them. So, the program will execute the second arm’s code, `continue`, which tells the program to go to the next iteration of the `loop` and ask for another guess. So, effectively, the program ignores all errors that `parse` might encounter! Now everything in the program should work as expected. Let’s try it: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s Running `target/debug/guessing_game` Guess the number! The secret number is: 61 Please input your guess. 10 You guessed: 10 Too small! Please input your guess. 99 You guessed: 99 Too big! Please input your guess. foo Please input your guess. 61 You guessed: 61 You win! Awesome! With one tiny final tweak, we will finish the guessing game. Recall that the program is still printing the secret number. That worked well for testing, but it ruins the game. Let’s delete the `println!` that outputs the secret number. Listing 2-6 shows the final code. Filename: src/main.rs use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } [Listing 2-6](https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html#listing-2-6) : Complete guessing game code At this point, you’ve successfully built the guessing game. Congratulations! This project was a hands-on way to introduce you to many new Rust concepts: `let`, `match`, functions, the use of external crates, and more. In the next few chapters, you’ll learn about these concepts in more detail. Chapter 3 covers concepts that most programming languages have, such as variables, data types, and functions, and shows how to use them in Rust. Chapter 4 explores ownership, a feature that makes Rust different from other languages. Chapter 5 discusses structs and method syntax, and Chapter 6 explains how enums work. --- # trait - Rust [trait](https://doc.rust-lang.org/stable/std/keyword.trait.html#) ------------------------------------------------------------------ Keyword trait Copy item path ============================ [Source](https://doc.rust-lang.org/stable/src/std/keyword_docs.rs.html#1958) Expand description A common interface for a group of types. A `trait` is like an interface that data types can implement. When a type implements a trait it can be treated abstractly as that trait using generics or trait objects. Traits can be made up of three varieties of associated items: * functions and methods * types * constants Traits may also contain additional type parameters. Those type parameters or the trait itself can be constrained by other traits. Traits can serve as markers or carry other logical semantics that aren’t expressed through their items. When a type implements that trait it is promising to uphold its contract. [`Send`](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") and [`Sync`](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") are two such marker traits present in the standard library. See the [Reference](https://doc.rust-lang.org/stable/reference/items/traits.html) for a lot more information on traits. [§](https://doc.rust-lang.org/stable/std/keyword.trait.html#examples) Examples ------------------------------------------------------------------------------ Traits are declared using the `trait` keyword. Types can implement them using [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) `Trait` [`for`](https://doc.rust-lang.org/stable/std/keyword.for.html) `Type`: trait Zero { const ZERO: Self; fn is_zero(&self) -> bool; } impl Zero for i32 { const ZERO: Self = 0; fn is_zero(&self) -> bool { *self == Self::ZERO } } assert_eq!(i32::ZERO, 0); assert!(i32::ZERO.is_zero()); assert!(!4.is_zero()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Zero+%7B%0A++++++++const+ZERO:+Self;%0A++++++++fn+is_zero(%26self)+-%3E+bool;%0A++++%7D%0A++++%0A++++impl+Zero+for+i32+%7B%0A++++++++const+ZERO:+Self+=+0;%0A++++%0A++++++++fn+is_zero(%26self)+-%3E+bool+%7B%0A++++++++++++*self+==+Self::ZERO%0A++++++++%7D%0A++++%7D%0A++++%0A++++assert_eq!(i32::ZERO,+0);%0A++++assert!(i32::ZERO.is_zero());%0A++++assert!(!4.is_zero());%0A%7D&edition=2024 "Run code") With an associated type: trait Builder { type Built; fn build(&self) -> Self::Built; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+Builder+%7B%0A++++++++type+Built;%0A++++%0A++++++++fn+build(%26self)+-%3E+Self::Built;%0A++++%7D%0A%7D&edition=2024 "Run code") Traits can be generic, with constraints or without: trait MaybeFrom { fn maybe_from(value: T) -> Option where Self: Sized; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+MaybeFrom%3CT%3E+%7B%0A++++++++fn+maybe_from(value:+T)+-%3E+Option%3CSelf%3E%0A++++++++where%0A++++++++++++Self:+Sized;%0A++++%7D%0A%7D&edition=2024 "Run code") Traits can build upon the requirements of other traits. In the example below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**: trait ThreeIterator: Iterator { fn next_three(&mut self) -> Option<[Self::Item; 3]>; } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+ThreeIterator:+Iterator+%7B%0A++++++++fn+next_three(%26mut+self)+-%3E+Option%3C%5BSelf::Item;+3%5D%3E;%0A++++%7D%0A%7D&edition=2024 "Run code") Traits can be used in functions, as parameters: fn debug_iter(it: I) where I::Item: std::fmt::Debug { for elem in it { println!("{elem:#?}"); } } // u8_len_1, u8_len_2 and u8_len_3 are equivalent fn u8_len_1(val: impl Into>) -> usize { val.into().len() } fn u8_len_2>>(val: T) -> usize { val.into().len() } fn u8_len_3(val: T) -> usize where T: Into>, { val.into().len() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++fn+debug_iter%3CI:+Iterator%3E(it:+I)+where+I::Item:+std::fmt::Debug+%7B%0A++++++++for+elem+in+it+%7B%0A++++++++++++println!(%22%7Belem:%23?%7D%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+u8_len_1,+u8_len_2+and+u8_len_3+are+equivalent%0A++++%0A++++fn+u8_len_1(val:+impl+Into%3CVec%3Cu8%3E%3E)+-%3E+usize+%7B%0A++++++++val.into().len()%0A++++%7D%0A++++%0A++++fn+u8_len_2%3CT:+Into%3CVec%3Cu8%3E%3E%3E(val:+T)+-%3E+usize+%7B%0A++++++++val.into().len()%0A++++%7D%0A++++%0A++++fn+u8_len_3%3CT%3E(val:+T)+-%3E+usize%0A++++where%0A++++++++T:+Into%3CVec%3Cu8%3E%3E,%0A++++%7B%0A++++++++val.into().len()%0A++++%7D%0A%7D&edition=2024 "Run code") Or as return types: fn from_zero_to(v: u8) -> impl Iterator { (0..v).into_iter() } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++fn+from_zero_to(v:+u8)+-%3E+impl+Iterator%3CItem+=+u8%3E+%7B%0A++++++++(0..v).into_iter()%0A++++%7D%0A%7D&edition=2024 "Run code") The use of the [`impl`](https://doc.rust-lang.org/stable/std/keyword.impl.html) keyword in this position allows the function writer to hide the concrete type as an implementation detail which can change without breaking user’s code. [§](https://doc.rust-lang.org/stable/std/keyword.trait.html#trait-objects) Trait objects ---------------------------------------------------------------------------------------- A _trait object_ is an opaque value of another type that implements a set of traits. A trait object implements all specified traits as well as their supertraits (if any). The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`. Only one `BaseTrait` can be used so this will not compile: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.trait.html# "This example deliberately fails to compile") trait A {} trait B {} let _: Box; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+A+%7B%7D%0A++++trait+B+%7B%7D%0A++++%0A++++let+_:+Box%3Cdyn+A+%2B+B%3E;%0A%7D&edition=2024 "Run code") Neither will this, which is a syntax error: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.trait.html# "This example deliberately fails to compile") trait A {} trait B {} let _: Box; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+A+%7B%7D%0A++++trait+B+%7B%7D%0A++++%0A++++let+_:+Box%3Cdyn+A+%2B+dyn+B%3E;%0A%7D&edition=2024 "Run code") On the other hand, this is correct: trait A {} let _: Box; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++trait+A+%7B%7D%0A++++%0A++++let+_:+Box%3Cdyn+A+%2B+Send+%2B+Sync%3E;%0A%7D&edition=2024 "Run code") The [Reference](https://doc.rust-lang.org/stable/reference/types/trait-object.html) has more information about trait objects, their limitations and the differences between editions. [§](https://doc.rust-lang.org/stable/std/keyword.trait.html#unsafe-traits) Unsafe traits ---------------------------------------------------------------------------------------- Some traits may be unsafe to implement. Using the [`unsafe`](https://doc.rust-lang.org/stable/std/keyword.unsafe.html) keyword in front of the trait’s declaration is used to mark this: unsafe trait UnsafeTrait {} unsafe impl UnsafeTrait for i32 {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++unsafe+trait+UnsafeTrait+%7B%7D%0A++++%0A++++unsafe+impl+UnsafeTrait+for+i32+%7B%7D%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/keyword.trait.html#differences-between-the-2015-and-2018-editions) Differences between the 2015 and 2018 editions ---------------------------------------------------------------------------------------------------------------------------------------------------------- In the 2015 edition the parameters pattern was not needed for traits: [ⓘ](https://doc.rust-lang.org/stable/std/keyword.trait.html# "This example runs with edition 2015") trait Tr { fn f(i32); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(anonymous_parameters)%5D%0A%0Afn+main()+%7B%0A++++trait+Tr+%7B%0A++++++++fn+f(i32);%0A++++%7D%0A%7D&edition=2015 "Run code") This behavior is no longer valid in edition 2018. --- # Modules - The Rust Reference Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Reference ================== [](https://doc.rust-lang.org/stable/reference/print.html "Print this book") [](https://github.com/rust-lang/reference/ "Git repository") [](https://github.com/rust-lang/reference/edit/master/src/items/modules.md "Suggest an edit") [\[items.mod\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod "items.mod") [\[items.mod.syntax\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.syntax "items.mod.syntax") **Syntax** [Module](https://doc.rust-lang.org/stable/reference/items/modules.html#railroad-Module) →       unsafe? mod [IDENTIFIER](https://doc.rust-lang.org/stable/reference/identifiers.html#grammar-IDENTIFIER) ;     | unsafe? mod [IDENTIFIER](https://doc.rust-lang.org/stable/reference/identifiers.html#grammar-IDENTIFIER) {         [InnerAttribute](https://doc.rust-lang.org/stable/reference/attributes.html#grammar-InnerAttribute) \*         [Item](https://doc.rust-lang.org/stable/reference/items.html#grammar-Item) \*       } Show Railroad Module unsafe mod IDENTIFIER ; unsafe mod IDENTIFIER { InnerAttribute Item } [\[items.mod.intro\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.intro "items.mod.intro") A module is a container for zero or more [items](https://doc.rust-lang.org/stable/reference/items.html) . [\[items.mod.def\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.def "items.mod.def") A _module item_ is a module, surrounded in braces, named, and prefixed with the keyword `mod`. A module item introduces a new, named module into the tree of modules making up a crate. [\[items.mod.nesting\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.nesting "items.mod.nesting") Modules can nest arbitrarily. An example of a module: #![allow(unused)] fn main() { mod math { type Complex = (f64, f64); fn sin(f: f64) -> f64 { /* ... */ unimplemented!(); } fn cos(f: f64) -> f64 { /* ... */ unimplemented!(); } fn tan(f: f64) -> f64 { /* ... */ unimplemented!(); } } } [\[items.mod.namespace\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.namespace "items.mod.namespace") Modules are defined in the [type namespace](https://doc.rust-lang.org/stable/reference/names/namespaces.html) of the module or block where they are located. [\[items.mod.multiple-items\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.multiple-items "items.mod.multiple-items") It is an error to define multiple items with the same name in the same namespace within a module. See the [scopes chapter](https://doc.rust-lang.org/stable/reference/names/scopes.html) for more details on restrictions and shadowing behavior. [\[items.mod.unsafe\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.unsafe "items.mod.unsafe") The `unsafe` keyword is syntactically allowed to appear before the `mod` keyword, but it is rejected at a semantic level. This allows macros to consume the syntax and make use of the `unsafe` keyword, before removing it from the token stream. [\[items.mod.outlined\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined "items.mod.outlined") [\[items.mod.outlined.intro\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.intro "items.mod.outlined.intro") A module without a body is loaded from an external file. When the module does not have a `path` attribute, the path to the file mirrors the logical [module path](https://doc.rust-lang.org/stable/reference/paths.html) . [\[items.mod.outlined.search\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.search "items.mod.outlined.search") Ancestor module path components are directories, and the module’s contents are in a file with the name of the module plus the `.rs` extension. For example, the following module structure can have this corresponding filesystem structure: | Module Path | Filesystem Path | File Contents | | --- | --- | --- | | `crate` | `lib.rs` | `mod util;` | | `crate::util` | `util.rs` | `mod config;` | | `crate::util::config` | `util/config.rs` | | [\[items.mod.outlined.search-mod\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.search-mod "items.mod.outlined.search-mod") Module filenames may also be the name of the module as a directory with the contents in a file named `mod.rs` within that directory. The above example can alternately be expressed with `crate::util`’s contents in a file named `util/mod.rs`. It is not allowed to have both `util.rs` and `util/mod.rs`. > Note > > Prior to `rustc` 1.30, using `mod.rs` files was the way to load a module with nested children. It is encouraged to use the new naming convention as it is more consistent, and avoids having many files named `mod.rs` within a project. [\[items.mod.outlined.path\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.path "items.mod.outlined.path") [\[items.mod.outlined.path.intro\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.path.intro "items.mod.outlined.path.intro") The directories and files used for loading external file modules can be influenced with the `path` attribute. [\[items.mod.outlined.path.search\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.path.search "items.mod.outlined.path.search") For `path` attributes on modules not inside inline module blocks, the file path is relative to the directory the source file is located. For example, the following code snippet would use the paths shown based on where it is located: #[path = "foo.rs"] mod c; | Source File | `c`’s File Location | `c`’s Module Path | | --- | --- | --- | | `src/a/b.rs` | `src/a/foo.rs` | `crate::a::b::c` | | `src/a/mod.rs` | `src/a/foo.rs` | `crate::a::c` | [\[items.mod.outlined.path.search-nested\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.outlined.path.search-nested "items.mod.outlined.path.search-nested") For `path` attributes inside inline module blocks, the relative location of the file path depends on the kind of source file the `path` attribute is located in. “mod-rs” source files are root modules (such as `lib.rs` or `main.rs`) and modules with files named `mod.rs`. “non-mod-rs” source files are all other module files. Paths for `path` attributes inside inline module blocks in a mod-rs file are relative to the directory of the mod-rs file including the inline module components as directories. For non-mod-rs files, it is the same except the path starts with a directory with the name of the non-mod-rs module. For example, the following code snippet would use the paths shown based on where it is located: mod inline { #[path = "other.rs"] mod inner; } | Source File | `inner`’s File Location | `inner`’s Module Path | | --- | --- | --- | | `src/a/b.rs` | `src/a/b/inline/other.rs` | `crate::a::b::inline::inner` | | `src/a/mod.rs` | `src/a/inline/other.rs` | `crate::a::inline::inner` | An example of combining the above rules of `path` attributes on inline modules and nested modules within (applies to both mod-rs and non-mod-rs files): #[path = "thread_files"] mod thread { // Load the `local_data` module from `thread_files/tls.rs` relative to // this source file's directory. #[path = "tls.rs"] mod local_data; } [\[items.mod.attributes\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.attributes "items.mod.attributes") [\[items.mod.attributes.intro\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.attributes.intro "items.mod.attributes.intro") Modules, like all items, accept outer attributes. They also accept inner attributes: either after `{` for a module with a body, or at the beginning of the source file, after the optional BOM and shebang. [\[items.mod.attributes.supported\]](https://doc.rust-lang.org/stable/reference/items/modules.html#r-items.mod.attributes.supported "items.mod.attributes.supported") The built-in attributes that have meaning on a module are [`cfg`](https://doc.rust-lang.org/stable/reference/conditional-compilation.html) , [`deprecated`](https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html#the-deprecated-attribute) , [`doc`](https://doc.rust-lang.org/stable/rustdoc/the-doc-attribute.html) , [the lint check attributes](https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html#lint-check-attributes) , [`path`](https://doc.rust-lang.org/stable/reference/items/modules.html#the-path-attribute) , and [`no_implicit_prelude`](https://doc.rust-lang.org/stable/reference/names/preludes.html#the-no_implicit_prelude-attribute) . Modules also accept macro attributes. --- # Unions - The Rust Reference Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Reference ================== [](https://doc.rust-lang.org/stable/reference/print.html "Print this book") [](https://github.com/rust-lang/reference/ "Git repository") [](https://github.com/rust-lang/reference/edit/master/src/items/unions.md "Suggest an edit") [\[items.union\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union "items.union") [\[items.union.syntax\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.syntax "items.union.syntax") **Syntax** [Union](https://doc.rust-lang.org/stable/reference/items/unions.html#railroad-Union) →     union [IDENTIFIER](https://doc.rust-lang.org/stable/reference/identifiers.html#grammar-IDENTIFIER) [GenericParams](https://doc.rust-lang.org/stable/reference/items/generics.html#grammar-GenericParams) ? [WhereClause](https://doc.rust-lang.org/stable/reference/items/generics.html#grammar-WhereClause) ? { [StructFields](https://doc.rust-lang.org/stable/reference/items/structs.html#grammar-StructFields) ? } Show Railroad Union union IDENTIFIER GenericParams WhereClause { StructFields } [\[items.union.intro\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.intro "items.union.intro") A union declaration uses the same syntax as a struct declaration, except with `union` in place of `struct`. [\[items.union.namespace\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.namespace "items.union.namespace") A union declaration defines the given name in the [type namespace](https://doc.rust-lang.org/stable/reference/names/namespaces.html) of the module or block where it is located. #![allow(unused)] fn main() { #[repr(C)] union MyUnion { f1: u32, f2: f32, } } [\[items.union.common-storage\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.common-storage "items.union.common-storage") The key property of unions is that all fields of a union share common storage. As a result, writes to one field of a union can overwrite its other fields, and size of a union is determined by the size of its largest field. [\[items.union.field-restrictions\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.field-restrictions "items.union.field-restrictions") Union field types are restricted to the following subset of types: [\[items.union.field-copy\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.field-copy "items.union.field-copy") * `Copy` types [\[items.union.field-references\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.field-references "items.union.field-references") * References (`&T` and `&mut T` for arbitrary `T`) [\[items.union.field-manually-drop\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.field-manually-drop "items.union.field-manually-drop") * `ManuallyDrop` (for arbitrary `T`) [\[items.union.field-tuple\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.field-tuple "items.union.field-tuple") * Tuples and arrays containing only allowed union field types [\[items.union.drop\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.drop "items.union.drop") This restriction ensures, in particular, that union fields never need to be dropped. Like for structs and enums, it is possible to `impl Drop` for a union to manually define what happens when it gets dropped. [\[items.union.fieldless\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fieldless "items.union.fieldless") Unions without any fields are not accepted by the compiler, but can be accepted by macros. [\[items.union.init\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.init "items.union.init") [\[items.union.init.intro\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.init.intro "items.union.init.intro") A value of a union type can be created using the same syntax that is used for struct types, except that it must specify exactly one field: #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } let u = MyUnion { f1: 1 }; } [\[items.union.init.result\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.init.result "items.union.init.result") The expression above creates a value of type `MyUnion` and initializes the storage using field `f1`. The union can be accessed using the same syntax as struct fields: #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } let u = MyUnion { f1: 1 }; let f = unsafe { u.f1 }; } [\[items.union.fields\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields "items.union.fields") [\[items.union.fields.intro\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields.intro "items.union.fields.intro") Unions have no notion of an “active field”. Instead, every union access just interprets the storage as the type of the field used for the access. [\[items.union.fields.read\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields.read "items.union.fields.read") Reading a union field reads the bits of the union at the field’s type. [\[items.union.fields.offset\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields.offset "items.union.fields.offset") Fields might have a non-zero offset (except when [the C representation](https://doc.rust-lang.org/stable/reference/type-layout.html#reprc-unions) is used); in that case the bits starting at the offset of the fields are read [\[items.union.fields.validity\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields.validity "items.union.fields.validity") It is the programmer’s responsibility to make sure that the data is valid at the field’s type. Failing to do so results in [undefined behavior](https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html) . For example, reading the value `3` from a field of the [boolean type](https://doc.rust-lang.org/stable/reference/types/boolean.html) is undefined behavior. Effectively, writing to and then reading from a union with [the C representation](https://doc.rust-lang.org/stable/reference/type-layout.html#reprc-unions) is analogous to a [`transmute`](https://doc.rust-lang.org/stable/core/intrinsics/fn.transmute.html) from the type used for writing to the type used for reading. [\[items.union.fields.read-safety\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields.read-safety "items.union.fields.read-safety") Consequently, all reads of union fields have to be placed in `unsafe` blocks: #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } let u = MyUnion { f1: 1 }; unsafe { let f = u.f1; } } Commonly, code using unions will provide safe wrappers around unsafe union field accesses. [\[items.union.fields.write-safety\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.fields.write-safety "items.union.fields.write-safety") In contrast, writes to union fields are safe, since they just overwrite arbitrary data, but cannot cause undefined behavior. (Note that union field types can never have drop glue, so a union field write will never implicitly drop anything.) [\[items.union.pattern\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.pattern "items.union.pattern") [\[items.union.pattern.intro\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.pattern.intro "items.union.pattern.intro") Another way to access union fields is to use pattern matching. [\[items.union.pattern.one-field\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.pattern.one-field "items.union.pattern.one-field") Pattern matching on union fields uses the same syntax as struct patterns, except that the pattern must specify exactly one field. [\[items.union.pattern.safety\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.pattern.safety "items.union.pattern.safety") Since pattern matching is like reading the union with a particular field, it has to be placed in `unsafe` blocks as well. #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } fn f(u: MyUnion) { unsafe { match u { MyUnion { f1: 10 } => { println!("ten"); } MyUnion { f2 } => { println!("{}", f2); } } } } } [\[items.union.pattern.subpattern\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.pattern.subpattern "items.union.pattern.subpattern") Pattern matching may match a union as a field of a larger structure. In particular, when using a Rust union to implement a C tagged union via FFI, this allows matching on the tag and the corresponding field simultaneously: #![allow(unused)] fn main() { #[repr(u32)] enum Tag { I, F } #[repr(C)] union U { i: i32, f: f32, } #[repr(C)] struct Value { tag: Tag, u: U, } fn is_zero(v: Value) -> bool { unsafe { match v { Value { tag: Tag::I, u: U { i: 0 } } => true, Value { tag: Tag::F, u: U { f: num } } if num == 0.0 => true, _ => false, } } } } [\[items.union.ref\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.ref "items.union.ref") [\[items.union.ref.intro\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.ref.intro "items.union.ref.intro") Since union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields. [\[items.union.ref.borrow\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.ref.borrow "items.union.ref.borrow") Borrow checking rules have to be adjusted to account for this fact. As a result, if one field of a union is borrowed, all its remaining fields are borrowed as well for the same lifetime. #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } // ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time fn test() { let mut u = MyUnion { f1: 1 }; unsafe { let b1 = &mut u.f1; // ---- first mutable borrow occurs here (via `u.f1`) let b2 = &mut u.f2; // ^^^^ second mutable borrow occurs here (via `u.f2`) *b1 = 5; } // - first borrow ends here assert_eq!(unsafe { u.f1 }, 5); } } [\[items.union.ref.usage\]](https://doc.rust-lang.org/stable/reference/items/unions.html#r-items.union.ref.usage "items.union.ref.usage") As you could see, in many aspects (except for layouts, safety, and ownership) unions behave exactly like structs, largely as a consequence of inheriting their syntactic shape from structs. This is also true for many unmentioned aspects of Rust language (such as privacy, name resolution, type inference, generics, trait implementations, inherent implementations, coherence, pattern checking, etc etc etc). --- # std::fmt - Rust [Module fmt](https://doc.rust-lang.org/stable/std/fmt/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module fmt Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/lib.rs.html#220) Expand description Utilities for formatting and printing `String`s. This module contains the runtime support for the [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") syntax extension. This macro is implemented in the compiler to emit calls to this module in order to format arguments at runtime into strings. [§](https://doc.rust-lang.org/stable/std/fmt/index.html#usage) Usage -------------------------------------------------------------------- The [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") macro is intended to be familiar to those coming from C’s `printf`/`fprintf` functions or Python’s `str.format` function. Some examples of the [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") extension are: format!("Hello"); // => "Hello" format!("Hello, {}!", "world"); // => "Hello, world!" format!("The number is {}", 1); // => "The number is 1" format!("{:?}", (3, 4)); // => "(3, 4)" format!("{value}", value=4); // => "4" let people = "Rustaceans"; format!("Hello {people}!"); // => "Hello Rustaceans!" format!("{} {}", 1, 2); // => "1 2" format!("{:04}", 42); // => "0042" with leading zeros format!("{:#?}", (100, 200)); // => "( // 100, // 200, // )" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++format!(%22Hello%22);+++++++++++++++++//+=%3E+%22Hello%22%0A++++format!(%22Hello,+%7B%7D!%22,+%22world%22);+++//+=%3E+%22Hello,+world!%22%0A++++format!(%22The+number+is+%7B%7D%22,+1);+++//+=%3E+%22The+number+is+1%22%0A++++format!(%22%7B:?%7D%22,+(3,+4));++++++++++//+=%3E+%22(3,+4)%22%0A++++format!(%22%7Bvalue%7D%22,+value=4);++++++//+=%3E+%224%22%0A++++let+people+=+%22Rustaceans%22;%0A++++format!(%22Hello+%7Bpeople%7D!%22);+++++++//+=%3E+%22Hello+Rustaceans!%22%0A++++format!(%22%7B%7D+%7B%7D%22,+1,+2);+++++++++++//+=%3E+%221+2%22%0A++++format!(%22%7B:04%7D%22,+42);+++++++++++++//+=%3E+%220042%22+with+leading+zeros%0A++++format!(%22%7B:%23?%7D%22,+(100,+200));%0A%7D&edition=2024 "Run code") From these, you can see that the first argument is a format string. It is required by the compiler for this to be a string literal; it cannot be a variable passed in (in order to perform validity checking). The compiler will then parse the format string and determine if the list of arguments provided is suitable to pass to this format string. To convert a single value to a string, use the [`to_string`](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string "ToString::to_string") method. This will use the [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") formatting trait. ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#positional-parameters) Positional parameters Each formatting argument is allowed to specify which value argument it’s referencing, and if omitted it is assumed to be “the next argument”. For example, the format string `{} {} {}` would take three parameters, and they would be formatted in the same order as they’re given. The format string `{2} {1} {0}`, however, would format arguments in reverse order. Things can get a little tricky once you start intermingling the two types of positional specifiers. The “next argument” specifier can be thought of as an iterator over the argument. Each time a “next argument” specifier is seen, the iterator advances. This leads to behavior like this: format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++format!(%22%7B1%7D+%7B%7D+%7B0%7D+%7B%7D%22,+1,+2);%0A%7D&edition=2024 "Run code") The internal iterator over the argument has not been advanced by the time the first `{}` is seen, so it prints the first argument. Then upon reaching the second `{}`, the iterator has advanced forward to the second argument. Essentially, parameters that explicitly name their argument do not affect parameters that do not name an argument in terms of positional specifiers. A format string is required to use all of its arguments, otherwise it is a compile-time error. You may refer to the same argument more than once in the format string. ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#named-parameters) Named parameters Rust itself does not have a Python-like equivalent of named parameters to a function, but the [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") macro is a syntax extension that allows it to leverage named parameters. Named parameters are listed at the end of the argument list and have the syntax: identifier '=' expression For example, the following [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") expressions all use named arguments: format!("{argument}", argument = "test"); // => "test" format!("{name} {}", 1, name = 2); // => "2 1" format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++format!(%22%7Bargument%7D%22,+argument+=+%22test%22);+++//+=%3E+%22test%22%0A++++format!(%22%7Bname%7D+%7B%7D%22,+1,+name+=+2);++++++++++//+=%3E+%222+1%22%0A++++format!(%22%7Ba%7D+%7Bc%7D+%7Bb%7D%22,+a=%22a%22,+b=%27b%27,+c=3);%0A%7D&edition=2024 "Run code") If a named parameter does not appear in the argument list, `format!` will reference a variable with that name in the current scope. let argument = 2 + 2; format!("{argument}"); // => "4" fn make_string(a: u32, b: &str) -> String { format!("{b} {a}") } make_string(927, "label"); // => "label 927" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++let+argument+=+2+%2B+2;%0A++++format!(%22%7Bargument%7D%22);+++//+=%3E+%224%22%0A++++%0A++++fn+make_string(a:+u32,+b:+%26str)+-%3E+String+%7B%0A++++++++format!(%22%7Bb%7D+%7Ba%7D%22)%0A++++%7D%0A++++make_string(927,+%22label%22);%0A%7D&edition=2024 "Run code") It is not valid to put positional parameters (those without names) after arguments that have names. Like with positional parameters, it is not valid to provide named parameters that are unused by the format string. [§](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-parameters) Formatting Parameters ---------------------------------------------------------------------------------------------------- Each argument being formatted can be transformed by a number of formatting parameters (corresponding to `format_spec` in [the syntax](https://doc.rust-lang.org/stable/std/fmt/index.html#syntax) ). These parameters affect the string representation of what’s being formatted. The colon `:` in format syntax divides identifier of the input data and the formatting options, the colon itself does not change anything, only introduces the options. let a = 5; let b = &a; println!("{a:e} {b:p}"); // => 5e0 0x7ffe37b7273c [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+5;%0A++++let+b+=+%26a;%0A++++println!(%22%7Ba:e%7D+%7Bb:p%7D%22);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#width) Width // All of these print "Hello x !" println!("Hello {:5}!", "x"); println!("Hello {:1$}!", "x", 5); println!("Hello {1:0$}!", 5, "x"); println!("Hello {:width$}!", "x", width = 5); let width = 5; println!("Hello {:width$}!", "x"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+All+of+these+print+%22Hello+x++++!%22%0A++++println!(%22Hello+%7B:5%7D!%22,+%22x%22);%0A++++println!(%22Hello+%7B:1%24%7D!%22,+%22x%22,+5);%0A++++println!(%22Hello+%7B1:0%24%7D!%22,+5,+%22x%22);%0A++++println!(%22Hello+%7B:width%24%7D!%22,+%22x%22,+width+=+5);%0A++++let+width+=+5;%0A++++println!(%22Hello+%7B:width%24%7D!%22,+%22x%22);%0A%7D&edition=2024 "Run code") This is a parameter for the “minimum width” that the format should take up. If the value’s string does not fill up this many characters, then the padding specified by fill/alignment will be used to take up the required space (see below). The value for the width can also be provided as a [`usize`](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") in the list of parameters by adding a postfix `$`, indicating that the second argument is a [`usize`](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") specifying the width. Referring to an argument with the dollar syntax does not affect the “next argument” counter, so it’s usually a good idea to refer to arguments by position, or use named arguments. ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#fillalignment) Fill/Alignment assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!"); assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(format!(%22Hello+%7B:%3C5%7D!%22,+%22x%22),++%22Hello+x++++!%22);%0A++++assert_eq!(format!(%22Hello+%7B:-%3C5%7D!%22,+%22x%22),+%22Hello+x----!%22);%0A++++assert_eq!(format!(%22Hello+%7B:%5E5%7D!%22,+%22x%22),++%22Hello+++x++!%22);%0A++++assert_eq!(format!(%22Hello+%7B:%3E5%7D!%22,+%22x%22),++%22Hello+++++x!%22);%0A%7D&edition=2024 "Run code") The optional fill character and alignment is provided normally in conjunction with the [`width`](https://doc.rust-lang.org/stable/std/fmt/index.html#width) parameter. It must be defined before `width`, right after the `:`. This indicates that if the value being formatted is smaller than `width` some extra characters will be printed around it. Filling comes in the following variants for different alignments: * `[fill]<` - the argument is left-aligned in `width` columns * `[fill]^` - the argument is center-aligned in `width` columns * `[fill]>` - the argument is right-aligned in `width` columns The default [fill/alignment](https://doc.rust-lang.org/stable/std/fmt/index.html#fillalignment) for non-numerics is a space and left-aligned. The default for numeric formatters is also a space character but with right-alignment. If the `0` flag (see below) is specified for numerics, then the implicit fill character is `0`. Note that alignment might not be implemented by some types. In particular, it is not generally implemented for the `Debug` trait. A good way to ensure padding is applied is to format your input, then pad this resulting string to obtain your output: println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !" [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++println!(%22Hello+%7B:%5E15%7D!%22,+format!(%22%7B:?%7D%22,+Some(%22hi%22)));%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#sign0) Sign/`#`/`0` assert_eq!(format!("Hello {:+}!", 5), "Hello +5!"); assert_eq!(format!("{:#x}!", 27), "0x1b!"); assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!"); assert_eq!(format!("{:#010x}!", 27), "0x0000001b!"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(format!(%22Hello+%7B:%2B%7D!%22,+5),+%22Hello+%2B5!%22);%0A++++assert_eq!(format!(%22%7B:%23x%7D!%22,+27),+%220x1b!%22);%0A++++assert_eq!(format!(%22Hello+%7B:05%7D!%22,+5),++%22Hello+00005!%22);%0A++++assert_eq!(format!(%22Hello+%7B:05%7D!%22,+-5),+%22Hello+-0005!%22);%0A++++assert_eq!(format!(%22%7B:%23010x%7D!%22,+27),+%220x0000001b!%22);%0A%7D&edition=2024 "Run code") These are all flags altering the behavior of the formatter. * `+` - This is intended for numeric types and indicates that the sign should always be printed. By default only the negative sign of signed values is printed, and the sign of positive or unsigned values is omitted. This flag indicates that the correct sign (`+` or `-`) should always be printed. * `-` - Currently not used * `#` - This flag indicates that the “alternate” form of printing should be used. The alternate forms are: * `#?` - pretty-print the [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") formatting (adds linebreaks and indentation) * `#x` - precedes the argument with a `0x` * `#X` - precedes the argument with a `0x` * `#b` - precedes the argument with a `0b` * `#o` - precedes the argument with a `0o` See [Formatting traits](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-traits) for a description of what the `?`, `x`, `X`, `b`, and `o` flags do. * `0` - This is used to indicate for integer formats that the padding to `width` should both be done with a `0` character as well as be sign-aware. A format like `{:08}` would yield `00000001` for the integer `1`, while the same format would yield `-0000001` for the integer `-1`. Notice that the negative version has one fewer zero than the positive version. Note that padding zeros are always placed after the sign (if any) and before the digits. When used together with the `#` flag, a similar rule applies: padding zeros are inserted after the prefix but before the digits. The prefix is included in the total width. This flag overrides the [fill character and alignment flag](https://doc.rust-lang.org/stable/std/fmt/index.html#fillalignment) . ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#precision) Precision For non-numeric types, this can be considered a “maximum width”. If the resulting string is longer than this width, then it is truncated down to this many characters and that truncated value is emitted with proper `fill`, `alignment` and `width` if those parameters are set. For integral types, this is ignored. For floating-point types, this indicates how many digits after the decimal point should be printed. There are three possible ways to specify the desired `precision`: 1. An integer `.N`: the integer `N` itself is the precision. 2. An integer or name followed by dollar sign `.N$`: use format _argument_ `N` (which must be a `usize`) as the precision. 3. An asterisk `.*`: `.*` means that this `{...}` is associated with _two_ format inputs rather than one: * If a format string in the fashion of `{:.*}` is used, then the first input holds the `usize` precision, and the second holds the value to print. * If a format string in the fashion of `{:.*}` is used, then the `` part refers to the value to print, and the `precision` is taken like it was specified with an omitted positional parameter (`{}` instead of `{:}`). For example, the following calls all print the same thing `Hello x is 0.01000`: // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)} println!("Hello {0} is {1:.5}", "x", 0.01); // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)} println!("Hello {1} is {2:.0$}", 5, "x", 0.01); // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)} println!("Hello {0} is {2:.1$}", "x", 5, 0.01); // Hello {next arg -> arg 0 ("x")} is {second of next two args -> arg 2 (0.01) with precision // specified in first of next two args -> arg 1 (5)} println!("Hello {} is {:.*}", "x", 5, 0.01); // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision // specified in next arg -> arg 0 (5)} println!("Hello {1} is {2:.*}", 5, "x", 0.01); // Hello {next arg -> arg 0 ("x")} is {arg 2 (0.01) with precision // specified in next arg -> arg 1 (5)} println!("Hello {} is {2:.*}", "x", 5, 0.01); // Hello {next arg -> arg 0 ("x")} is {arg "number" (0.01) with precision specified // in arg "prec" (5)} println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++//+Hello+%7Barg+0+(%22x%22)%7D+is+%7Barg+1+(0.01)+with+precision+specified+inline+(5)%7D%0A++++println!(%22Hello+%7B0%7D+is+%7B1:.5%7D%22,+%22x%22,+0.01);%0A++++%0A++++//+Hello+%7Barg+1+(%22x%22)%7D+is+%7Barg+2+(0.01)+with+precision+specified+in+arg+0+(5)%7D%0A++++println!(%22Hello+%7B1%7D+is+%7B2:.0%24%7D%22,+5,+%22x%22,+0.01);%0A++++%0A++++//+Hello+%7Barg+0+(%22x%22)%7D+is+%7Barg+2+(0.01)+with+precision+specified+in+arg+1+(5)%7D%0A++++println!(%22Hello+%7B0%7D+is+%7B2:.1%24%7D%22,+%22x%22,+5,+0.01);%0A++++%0A++++//+Hello+%7Bnext+arg+-%3E+arg+0+(%22x%22)%7D+is+%7Bsecond+of+next+two+args+-%3E+arg+2+(0.01)+with+precision%0A++++//++++++++++++++++++++++++++specified+in+first+of+next+two+args+-%3E+arg+1+(5)%7D%0A++++println!(%22Hello+%7B%7D+is+%7B:.*%7D%22,++++%22x%22,+5,+0.01);%0A++++%0A++++//+Hello+%7Barg+1+(%22x%22)%7D+is+%7Barg+2+(0.01)+with+precision%0A++++//++++++++++++++++++++++++++specified+in+next+arg+-%3E+arg+0+(5)%7D%0A++++println!(%22Hello+%7B1%7D+is+%7B2:.*%7D%22,++5,+%22x%22,+0.01);%0A++++%0A++++//+Hello+%7Bnext+arg+-%3E+arg+0+(%22x%22)%7D+is+%7Barg+2+(0.01)+with+precision%0A++++//++++++++++++++++++++++++++specified+in+next+arg+-%3E+arg+1+(5)%7D%0A++++println!(%22Hello+%7B%7D+is+%7B2:.*%7D%22,+++%22x%22,+5,+0.01);%0A++++%0A++++//+Hello+%7Bnext+arg+-%3E+arg+0+(%22x%22)%7D+is+%7Barg+%22number%22+(0.01)+with+precision+specified%0A++++//++++++++++++++++++++++++++in+arg+%22prec%22+(5)%7D%0A++++println!(%22Hello+%7B%7D+is+%7Bnumber:.prec%24%7D%22,+%22x%22,+prec+=+5,+number+=+0.01);%0A%7D&edition=2024 "Run code") While these: println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++println!(%22%7B%7D,+%60%7Bname:.*%7D%60+has+3+fractional+digits%22,+%22Hello%22,+3,+name=1234.56);%0A++++println!(%22%7B%7D,+%60%7Bname:.*%7D%60+has+3+characters%22,+%22Hello%22,+3,+name=%221234.56%22);%0A++++println!(%22%7B%7D,+%60%7Bname:%3E8.*%7D%60+has+3+right-aligned+characters%22,+%22Hello%22,+3,+name=%221234.56%22);%0A%7D&edition=2024 "Run code") print three significantly different things: Hello, `1234.560` has 3 fractional digits Hello, `123` has 3 characters Hello, ` 123` has 3 right-aligned characters When truncating these values, Rust uses [round half-to-even](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) , which is the default rounding mode in IEEE 754. For example, print!("{0:.1$e}", 12345, 3); print!("{0:.1$e}", 12355, 3); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++print!(%22%7B0:.1%24e%7D%22,+12345,+3);%0A++++print!(%22%7B0:.1%24e%7D%22,+12355,+3);%0A%7D&edition=2024 "Run code") Would return: 1.234e4 1.236e4 ### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#localization) Localization In some programming languages, the behavior of string formatting functions depends on the operating system’s locale setting. The format functions provided by Rust’s standard library do not have any concept of locale and will produce the same results on all systems regardless of user configuration. For example, the following code will always print `1.5` even if the system locale uses a decimal separator other than a dot. println!("The value is {}", 1.5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++println!(%22The+value+is+%7B%7D%22,+1.5);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/fmt/index.html#escaping) Escaping -------------------------------------------------------------------------- The literal characters `{` and `}` may be included in a string by preceding them with the same character. For example, the `{` character is escaped with `{{` and the `}` character is escaped with `}}`. assert_eq!(format!("Hello {{}}"), "Hello {}"); assert_eq!(format!("{{ Hello"), "{ Hello"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(format!(%22Hello+%7B%7B%7D%7D%22),+%22Hello+%7B%7D%22);%0A++++assert_eq!(format!(%22%7B%7B+Hello%22),+%22%7B+Hello%22);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/fmt/index.html#syntax) Syntax ---------------------------------------------------------------------- To summarize, here you can find the full grammar of format strings. The syntax for the formatting language used is drawn from other languages, so it should not be too alien. Arguments are formatted with Python-like syntax, meaning that arguments are surrounded by `{}` instead of the C-like `%`. The actual grammar for the formatting syntax is: format_string := text [ maybe_format text ] * maybe_format := '{' '{' | '}' '}' | format format := '{' [ argument ] [ ':' format_spec ] [ ws ] * '}' argument := integer | identifier format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type] fill := character align := '<' | '^' | '>' sign := '+' | '-' width := count precision := count | '*' type := '?' | 'x?' | 'X?' | 'o' | 'x' | 'X' | 'p' | 'b' | 'e' | 'E' count := parameter | integer parameter := argument '$' In the above grammar, * `text` must not contain any `'{'` or `'}'` characters, * `ws` is any character for which [`char::is_whitespace`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_whitespace "method char::is_whitespace") returns `true`, has no semantic meaning and is completely optional, * `integer` is a decimal integer that may contain leading zeroes and must fit into an `usize` and * `identifier` is an `IDENTIFIER_OR_KEYWORD` (not an `IDENTIFIER`) as defined by the [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) . [§](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-traits) Formatting traits -------------------------------------------------------------------------------------------- When requesting that an argument be formatted with a particular type, you are actually requesting that an argument ascribes to a particular trait. This allows multiple actual types to be formatted via `{:x}` (like [`i8`](https://doc.rust-lang.org/stable/std/primitive.i8.html "primitive i8") as well as [`isize`](https://doc.rust-lang.org/stable/std/primitive.isize.html "primitive isize") ). The current mapping of types to traits is: * _nothing_ ⇒ [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") * `?` ⇒ [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") * `x?` ⇒ [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") with lower-case hexadecimal integers * `X?` ⇒ [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") with upper-case hexadecimal integers * `o` ⇒ [`Octal`](https://doc.rust-lang.org/stable/std/fmt/trait.Octal.html "trait std::fmt::Octal") * `x` ⇒ [`LowerHex`](https://doc.rust-lang.org/stable/std/fmt/trait.LowerHex.html "trait std::fmt::LowerHex") * `X` ⇒ [`UpperHex`](https://doc.rust-lang.org/stable/std/fmt/trait.UpperHex.html "trait std::fmt::UpperHex") * `p` ⇒ [`Pointer`](https://doc.rust-lang.org/stable/std/fmt/trait.Pointer.html "trait std::fmt::Pointer") * `b` ⇒ [`Binary`](https://doc.rust-lang.org/stable/std/fmt/trait.Binary.html "trait std::fmt::Binary") * `e` ⇒ [`LowerExp`](https://doc.rust-lang.org/stable/std/fmt/trait.LowerExp.html "trait std::fmt::LowerExp") * `E` ⇒ [`UpperExp`](https://doc.rust-lang.org/stable/std/fmt/trait.UpperExp.html "trait std::fmt::UpperExp") What this means is that any type of argument which implements the [`fmt::Binary`](https://doc.rust-lang.org/stable/std/fmt/trait.Binary.html "trait std::fmt::Binary") trait can then be formatted with `{:b}`. Implementations are provided for these traits for a number of primitive types by the standard library as well. If no format is specified (as in `{}` or `{:6}`), then the format trait used is the [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") trait. When implementing a format trait for your own type, you will have to implement a method of the signature: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(dead_code)%5D%0A%0Afn+main()+%7B%0A++++use+std::fmt;%0A++++struct+Foo;+//+our+custom+type%0A++++impl+fmt::Display+for+Foo+%7B%0A++++fn+fmt(%26self,+f:+%26mut+fmt::Formatter%3C%27_%3E)+-%3E+fmt::Result+%7B%0A++++write!(f,+%22testing,+testing%22)%0A++++%7D+%7D%0A%7D&edition=2024 "Run code") Your type will be passed as `self` by-reference, and then the function should emit output into the Formatter `f` which implements `fmt::Write`. It is up to each format trait implementation to correctly adhere to the requested formatting parameters. The values of these parameters can be accessed with methods of the [`Formatter`](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") struct. In order to help with this, the [`Formatter`](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") struct also provides some helper methods. Additionally, the return value of this function is [`fmt::Result`](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "fmt::Result") which is a type alias of `[Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "std::result::Result") <(), [std::fmt::Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "fmt::Error") >`. Formatting implementations should ensure that they propagate errors from the [`Formatter`](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") (e.g., when calling [`write!`](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") ). However, they should never return errors spuriously. That is, a formatting implementation must and may only return an error if the passed-in [`Formatter`](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") returns an error. This is because, contrary to what the function signature might suggest, string formatting is an infallible operation. This function only returns a [`Result`](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") because writing to the underlying stream might fail and it must provide a way to propagate the fact that an error has occurred back up the stack. An example of implementing the formatting traits would look like: use std::fmt; #[derive(Debug)] struct Vector2D { x: isize, y: isize, } impl fmt::Display for Vector2D { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // The `f` value implements the `Write` trait, which is what the // write! macro is expecting. Note that this formatting ignores the // various flags provided to format strings. write!(f, "({}, {})", self.x, self.y) } } // Different traits allow different forms of output of a type. The meaning // of this format is to print the magnitude of a vector. impl fmt::Binary for Vector2D { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let magnitude = (self.x * self.x + self.y * self.y) as f64; let magnitude = magnitude.sqrt(); // Respect the formatting flags by using the helper method // `pad_integral` on the Formatter object. See the method // documentation for details, and the function `pad` can be used // to pad strings. let decimals = f.precision().unwrap_or(3); let string = format!("{magnitude:.decimals$}"); f.pad_integral(true, "", &string) } } fn main() { let myvector = Vector2D { x: 3, y: 4 }; println!("{myvector}"); // => "(3, 4)" println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}" println!("{myvector:10.3b}"); // => " 5.000" } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::fmt;%0A%0A%23%5Bderive(Debug)%5D%0Astruct+Vector2D+%7B%0A++++x:+isize,%0A++++y:+isize,%0A%7D%0A%0Aimpl+fmt::Display+for+Vector2D+%7B%0A++++fn+fmt(%26self,+f:+%26mut+fmt::Formatter%3C%27_%3E)+-%3E+fmt::Result+%7B%0A++++++++//+The+%60f%60+value+implements+the+%60Write%60+trait,+which+is+what+the%0A++++++++//+write!+macro+is+expecting.+Note+that+this+formatting+ignores+the%0A++++++++//+various+flags+provided+to+format+strings.%0A++++++++write!(f,+%22(%7B%7D,+%7B%7D)%22,+self.x,+self.y)%0A++++%7D%0A%7D%0A%0A//+Different+traits+allow+different+forms+of+output+of+a+type.+The+meaning%0A//+of+this+format+is+to+print+the+magnitude+of+a+vector.%0Aimpl+fmt::Binary+for+Vector2D+%7B%0A++++fn+fmt(%26self,+f:+%26mut+fmt::Formatter%3C%27_%3E)+-%3E+fmt::Result+%7B%0A++++++++let+magnitude+=+(self.x+*+self.x+%2B+self.y+*+self.y)+as+f64;%0A++++++++let+magnitude+=+magnitude.sqrt();%0A%0A++++++++//+Respect+the+formatting+flags+by+using+the+helper+method%0A++++++++//+%60pad_integral%60+on+the+Formatter+object.+See+the+method%0A++++++++//+documentation+for+details,+and+the+function+%60pad%60+can+be+used%0A++++++++//+to+pad+strings.%0A++++++++let+decimals+=+f.precision().unwrap_or(3);%0A++++++++let+string+=+format!(%22%7Bmagnitude:.decimals%24%7D%22);%0A++++++++f.pad_integral(true,+%22%22,+%26string)%0A++++%7D%0A%7D%0A%0Afn+main()+%7B%0A++++let+myvector+=+Vector2D+%7B+x:+3,+y:+4+%7D;%0A%0A++++println!(%22%7Bmyvector%7D%22);+++++++//+=%3E+%22(3,+4)%22%0A++++println!(%22%7Bmyvector:?%7D%22);+++++//+=%3E+%22Vector2D+%7Bx:+3,+y:4%7D%22%0A++++println!(%22%7Bmyvector:10.3b%7D%22);+//+=%3E+%22+++++5.000%22%0A%7D&edition=2024 "Run code") #### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#fmtdisplay-vs-fmtdebug) `fmt::Display` vs `fmt::Debug` These two formatting traits have distinct purposes: * [`fmt::Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") implementations assert that the type can be faithfully represented as a UTF-8 string at all times. It is **not** expected that all types implement the [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") trait. * [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementations should be implemented for **all** public types. Output will typically represent the internal state as faithfully as possible. The purpose of the [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") trait is to facilitate debugging Rust code. In most cases, using `#[derive(Debug)]` is sufficient and recommended. Some examples of the output from both traits: assert_eq!(format!("{} {:?}", 3, 4), "3 4"); assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(format!(%22%7B%7D+%7B:?%7D%22,+3,+4),+%223+4%22);%0A++++assert_eq!(format!(%22%7B%7D+%7B:?%7D%22,+%27a%27,+%27b%27),+%22a+%27b%27%22);%0A++++assert_eq!(format!(%22%7B%7D+%7B:?%7D%22,+%22foo%5Cn%22,+%22bar%5Cn%22),+%22foo%5Cn+%5C%22bar%5C%5Cn%5C%22%22);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/fmt/index.html#related-macros) Related macros -------------------------------------------------------------------------------------- There are a number of related macros in the [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html "macro std::format") family. The ones that are currently implemented are: [ⓘ](https://doc.rust-lang.org/stable/std/fmt/index.html# "This example is not tested") format! // described above write! // first argument is either a &mut io::Write or a &mut fmt::Write, the destination writeln! // same as write but appends a newline print! // the format string is printed to the standard output println! // same as print but appends a newline eprint! // the format string is printed to the standard error eprintln! // same as eprint but appends a newline format_args! // described below. [](https://play.rust-lang.org/?code=format!++++++//+described+above%0Awrite!+++++++//+first+argument+is+either+a+%26mut+io::Write+or+a+%26mut+fmt::Write,+the+destination%0Awriteln!+++++//+same+as+write+but+appends+a+newline%0Aprint!+++++++//+the+format+string+is+printed+to+the+standard+output%0Aprintln!+++++//+same+as+print+but+appends+a+newline%0Aeprint!++++++//+the+format+string+is+printed+to+the+standard+error%0Aeprintln!++++//+same+as+eprint+but+appends+a+newline%0Aformat_args!+//+described+below.&edition=2024 "Run code") #### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#write) `write!` [`write!`](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") and [`writeln!`](https://doc.rust-lang.org/stable/std/macro.writeln.html "macro std::writeln") are two macros which are used to emit the format string to a specified stream. This is used to prevent intermediate allocations of format strings and instead directly write the output. Under the hood, this function is actually invoking the [`write_fmt`](https://doc.rust-lang.org/stable/std/io/trait.Write.html#method.write_fmt) function defined on the [`std::io::Write`](https://doc.rust-lang.org/stable/std/io/trait.Write.html) and the [`std::fmt::Write`](https://doc.rust-lang.org/stable/std/fmt/trait.Write.html) trait. Example usage is: use std::io::Write; let mut w = Vec::new(); write!(&mut w, "Hello {}!", "world"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++use+std::io::Write;%0A++++let+mut+w+=+Vec::new();%0A++++write!(%26mut+w,+%22Hello+%7B%7D!%22,+%22world%22);%0A%7D&edition=2024 "Run code") #### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#print) `print!` This and [`println!`](https://doc.rust-lang.org/stable/std/macro.println.html "println!") emit their output to stdout. Similarly to the [`write!`](https://doc.rust-lang.org/stable/std/macro.write.html "macro std::write") macro, the goal of these macros is to avoid intermediate allocations when printing output. Example usage is: print!("Hello {}!", "world"); println!("I have a newline {}", "character at the end"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++print!(%22Hello+%7B%7D!%22,+%22world%22);%0A++++println!(%22I+have+a+newline+%7B%7D%22,+%22character+at+the+end%22);%0A%7D&edition=2024 "Run code") #### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#eprint) `eprint!` The [`eprint!`](https://doc.rust-lang.org/stable/std/macro.eprint.html "eprint!") and [`eprintln!`](https://doc.rust-lang.org/stable/std/macro.eprintln.html "eprintln!") macros are identical to [`print!`](https://doc.rust-lang.org/stable/std/macro.print.html "print!") and [`println!`](https://doc.rust-lang.org/stable/std/macro.println.html "println!") , respectively, except they emit their output to stderr. #### [§](https://doc.rust-lang.org/stable/std/fmt/index.html#format_args) `format_args!` [`format_args!`](https://doc.rust-lang.org/stable/std/macro.format_args.html "format_args!") is a curious macro used to safely pass around an opaque object describing the format string. This object does not require any heap allocations to create, and it only references information on the stack. Under the hood, all of the related macros are implemented in terms of this. First off, some example usage is: use std::fmt; use std::io::{self, Write}; let mut some_writer = io::stdout(); write!(&mut some_writer, "{}", format_args!("print with a {}", "macro")); fn my_fmt_fn(args: fmt::Arguments<'_>) { write!(&mut io::stdout(), "{args}"); } my_fmt_fn(format_args!(", or a {} too", "function")); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(unused_must_use)%5D%0A%0Afn+main()+%7B%0A++++use+std::fmt;%0A++++use+std::io::%7Bself,+Write%7D;%0A++++%0A++++let+mut+some_writer+=+io::stdout();%0A++++write!(%26mut+some_writer,+%22%7B%7D%22,+format_args!(%22print+with+a+%7B%7D%22,+%22macro%22));%0A++++%0A++++fn+my_fmt_fn(args:+fmt::Arguments%3C%27_%3E)+%7B%0A++++++++write!(%26mut+io::stdout(),+%22%7Bargs%7D%22);%0A++++%7D%0A++++my_fmt_fn(format_args!(%22,+or+a+%7B%7D+too%22,+%22function%22));%0A%7D&edition=2024 "Run code") The result of the [`format_args!`](https://doc.rust-lang.org/stable/std/macro.format_args.html "format_args!") macro is a value of type [`fmt::Arguments`](https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html "fmt::Arguments") . This structure can then be passed to the [`write`](https://doc.rust-lang.org/stable/std/fmt/fn.write.html "fmt::write") and [`format`](https://doc.rust-lang.org/stable/std/fmt/fn.format.html "fmt::format") functions inside this module in order to process the format string. The goal of this macro is to even further prevent intermediate allocations when dealing with formatting strings. For example, a logging library could use the standard formatting syntax, but it would internally pass around this structure until it has been determined where output should go to. Structs[§](https://doc.rust-lang.org/stable/std/fmt/index.html#structs) ------------------------------------------------------------------------ [Arguments](https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html "struct std::fmt::Arguments") This structure represents a safely precompiled version of a format string and its arguments. This cannot be generated at runtime because it cannot safely be done, so no constructors are given and the fields are private to prevent modification. [DebugList](https://doc.rust-lang.org/stable/std/fmt/struct.DebugList.html "struct std::fmt::DebugList") A struct to help with [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementations. [DebugMap](https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html "struct std::fmt::DebugMap") A struct to help with [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementations. [DebugSet](https://doc.rust-lang.org/stable/std/fmt/struct.DebugSet.html "struct std::fmt::DebugSet") A struct to help with [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementations. [DebugStruct](https://doc.rust-lang.org/stable/std/fmt/struct.DebugStruct.html "struct std::fmt::DebugStruct") A struct to help with [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementations. [DebugTuple](https://doc.rust-lang.org/stable/std/fmt/struct.DebugTuple.html "struct std::fmt::DebugTuple") A struct to help with [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") implementations. [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") The error type which is returned from formatting a message into a stream. [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") Configuration for formatting. [FormattingOptions](https://doc.rust-lang.org/stable/std/fmt/struct.FormattingOptions.html "struct std::fmt::FormattingOptions") Experimental Options for formatting. [FromFn](https://doc.rust-lang.org/stable/std/fmt/struct.FromFn.html "struct std::fmt::FromFn") Experimental Implements [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") and [`fmt::Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") using a function. Enums[§](https://doc.rust-lang.org/stable/std/fmt/index.html#enums) -------------------------------------------------------------------- [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") Possible alignments returned by `Formatter::align` [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") Experimental Specifies whether the [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") trait should use lower-/upper-case hexadecimal or normal integers. [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") Experimental The signedness of a [`Formatter`](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") (or of a [`FormattingOptions`](https://doc.rust-lang.org/stable/std/fmt/struct.FormattingOptions.html "struct std::fmt::FormattingOptions") ). Traits[§](https://doc.rust-lang.org/stable/std/fmt/index.html#traits) ---------------------------------------------------------------------- [Binary](https://doc.rust-lang.org/stable/std/fmt/trait.Binary.html "trait std::fmt::Binary") `b` formatting. [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") `?` formatting. [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") Format trait for an empty format, `{}`. [LowerExp](https://doc.rust-lang.org/stable/std/fmt/trait.LowerExp.html "trait std::fmt::LowerExp") `e` formatting. [LowerHex](https://doc.rust-lang.org/stable/std/fmt/trait.LowerHex.html "trait std::fmt::LowerHex") `x` formatting. [Octal](https://doc.rust-lang.org/stable/std/fmt/trait.Octal.html "trait std::fmt::Octal") `o` formatting. [Pointer](https://doc.rust-lang.org/stable/std/fmt/trait.Pointer.html "trait std::fmt::Pointer") `p` formatting. [UpperExp](https://doc.rust-lang.org/stable/std/fmt/trait.UpperExp.html "trait std::fmt::UpperExp") `E` formatting. [UpperHex](https://doc.rust-lang.org/stable/std/fmt/trait.UpperHex.html "trait std::fmt::UpperHex") `X` formatting. [Write](https://doc.rust-lang.org/stable/std/fmt/trait.Write.html "trait std::fmt::Write") A trait for writing or formatting into Unicode-accepting buffers or streams. Functions[§](https://doc.rust-lang.org/stable/std/fmt/index.html#functions) ---------------------------------------------------------------------------- [format](https://doc.rust-lang.org/stable/std/fmt/fn.format.html "fn std::fmt::format") Takes an [`Arguments`](https://doc.rust-lang.org/stable/std/fmt/struct.Arguments.html "struct std::fmt::Arguments") struct and returns the resulting formatted string. [write](https://doc.rust-lang.org/stable/std/fmt/fn.write.html "fn std::fmt::write") Takes an output stream and an `Arguments` struct that can be precompiled with the `format_args!` macro. [from\_fn](https://doc.rust-lang.org/stable/std/fmt/fn.from_fn.html "fn std::fmt::from_fn") Experimental Creates a type whose [`fmt::Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") and [`fmt::Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") impls are provided with the function `f`. Type Aliases[§](https://doc.rust-lang.org/stable/std/fmt/index.html#types) --------------------------------------------------------------------------- [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") The type returned by formatter methods. Derive Macros[§](https://doc.rust-lang.org/stable/std/fmt/index.html#derives) ------------------------------------------------------------------------------ [Debug](https://doc.rust-lang.org/stable/std/fmt/derive.Debug.html "derive std::fmt::Debug") Derive macro generating an impl of the trait `Debug`. --- # std::ptr - Rust [Module ptr](https://doc.rust-lang.org/stable/std/ptr/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module ptr Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#284) Expand description Manually manage memory through raw pointers. _[See also the pointer primitive types](https://doc.rust-lang.org/stable/std/primitive.pointer.html "primitive pointer") ._ [§](https://doc.rust-lang.org/stable/std/ptr/index.html#safety) Safety ---------------------------------------------------------------------- Many functions in this module take raw pointers as arguments and read from or write to them. For this to be safe, these pointers must be _valid_ for the given access. Whether a pointer is valid depends on the operation it is used for (read or write), and the extent of the memory that is accessed (i.e., how many bytes are read/written) – it makes no sense to ask “is this pointer valid”; one has to ask “is this pointer valid for a given access”. Most functions use `*mut T` and `*const T` to access only a single value, in which case the documentation omits the size and implicitly assumes it to be `size_of::()` bytes. The precise rules for validity are not determined yet. The guarantees that are provided at this point are very minimal: * For memory accesses of [size zero](https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#zero-sized-types-zsts) , _every_ pointer is valid, including the [null](https://doc.rust-lang.org/stable/std/ptr/fn.null.html "fn std::ptr::null") pointer. The following points are only concerned with non-zero-sized accesses. * A [null](https://doc.rust-lang.org/stable/std/ptr/fn.null.html "fn std::ptr::null") pointer is _never_ valid. * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer be _dereferenceable_. The [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance) of the pointer is used to determine which [allocation](https://doc.rust-lang.org/stable/std/ptr/index.html#allocation) it is derived from; a pointer is dereferenceable if the memory range of the given size starting at the pointer is entirely contained within the bounds of that allocation. Note that in Rust, every (stack-allocated) variable is considered a separate allocation. * All accesses performed by functions in this module are _non-atomic_ in the sense of [atomic operations](https://doc.rust-lang.org/stable/std/sync/atomic/index.html "mod std::sync::atomic") used to synchronize between threads. This means it is undefined behavior to perform two concurrent accesses to the same location from different threads unless both accesses only read from memory. Notice that this explicitly includes [`read_volatile`](https://doc.rust-lang.org/stable/std/ptr/fn.read_volatile.html "fn std::ptr::read_volatile") and [`write_volatile`](https://doc.rust-lang.org/stable/std/ptr/fn.write_volatile.html "fn std::ptr::write_volatile") : Volatile accesses cannot be used for inter-thread synchronization, regardless of whether they are acting on Rust memory or not. * The result of casting a reference to a pointer is valid for as long as the underlying allocation is live and no reference (just raw pointers) is used to access the same memory. That is, reference and pointer accesses cannot be interleaved. These axioms, along with careful use of [`offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset "method pointer::offset") for pointer arithmetic, are enough to correctly implement many useful things in unsafe code. Stronger guarantees will be provided eventually, as the [aliasing](https://doc.rust-lang.org/stable/nomicon/aliasing.html) rules are being determined. For more information, see the [book](https://doc.rust-lang.org/stable/book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer) as well as the section in the reference devoted to [undefined behavior](https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html) . We say that a pointer is “dangling” if it is not valid for any non-zero-sized accesses. This means out-of-bounds pointers, pointers to freed memory, null pointers, and pointers created with [`NonNull::dangling`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.dangling "associated function std::ptr::NonNull::dangling") are all dangling. ### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#alignment) Alignment Valid raw pointers as defined above are not necessarily properly aligned (where “proper” alignment is defined by the pointee type, i.e., `*const T` must be aligned to `align_of::()`). However, most functions require their arguments to be properly aligned, and will explicitly state this requirement in their documentation. Notable exceptions to this are [`read_unaligned`](https://doc.rust-lang.org/stable/std/ptr/fn.read_unaligned.html "fn std::ptr::read_unaligned") and [`write_unaligned`](https://doc.rust-lang.org/stable/std/ptr/fn.write_unaligned.html "fn std::ptr::write_unaligned") . When a function requires proper alignment, it does so even if the access has size 0, i.e., even if memory is not actually touched. Consider using [`NonNull::dangling`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.dangling "associated function std::ptr::NonNull::dangling") in such cases. ### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#pointer-to-reference-conversion) Pointer to reference conversion When converting a pointer to a reference (e.g. via `&*ptr` or `&mut *ptr`), there are several rules that must be followed: * The pointer must be properly aligned. * It must be non-null. * It must be “dereferenceable” in the sense defined above. * The pointer must point to a [valid value](https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html#invalid-values) of type `T`. * You must enforce Rust’s aliasing rules. The exact aliasing rules are not decided yet, so we only give a rough overview here. The rules also depend on whether a mutable or a shared reference is being created. * When creating a mutable reference, then while this reference exists, the memory it points to must not get accessed (read or written) through any other pointer or reference not derived from this reference. * When creating a shared reference, then while this reference exists, the memory it points to must not get mutated (except inside `UnsafeCell`). If a pointer follows all of these rules, it is said to be _convertible to a (mutable or shared) reference_. These rules apply even if the result is unused! (The part about being initialized is not yet fully decided, but until it is, the only safe approach is to ensure that they are indeed initialized.) An example of the implications of the above rules is that an expression such as `unsafe { &*(0 as *const u8) }` is Immediate Undefined Behavior. ### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#allocation) Allocation An _allocation_ is a subset of program memory which is addressable from Rust, and within which pointer arithmetic is possible. Examples of allocations include heap allocations, stack-allocated variables, statics, and consts. The safety preconditions of some Rust operations - such as `offset` and field projections (`expr.field`) - are defined in terms of the allocations on which they operate. An allocation has a base address, a size, and a set of memory addresses. It is possible for an allocation to have zero size, but such an allocation will still have a base address. The base address of an allocation is not necessarily unique. While it is currently the case that an allocation always has a set of memory addresses which is fully contiguous (i.e., has no “holes”), there is no guarantee that this will not change in the future. Allocations must behave like “normal” memory: in particular, reads must not have side-effects, and writes must become visible to other threads using the usual synchronization primitives. For any allocation with `base` address, `size`, and a set of `addresses`, the following are guaranteed: * For all addresses `a` in `addresses`, `a` is in the range `base .. (base + size)` (note that this requires `a < base + size`, not `a <= base + size`) * `base` is not equal to [`null()`](https://doc.rust-lang.org/stable/std/ptr/fn.null.html "fn std::ptr::null") (i.e., the address with the numerical value 0) * `base + size <= usize::MAX` * `size <= isize::MAX` As a consequence of these guarantees, given any address `a` within the set of addresses of an allocation: * It is guaranteed that `a - base` does not overflow `isize` * It is guaranteed that `a - base` is non-negative * It is guaranteed that, given `o = a - base` (i.e., the offset of `a` within the allocation), `base + o` will not wrap around the address space (in other words, will not overflow `usize`) [§](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance) Provenance ------------------------------------------------------------------------------ Pointers are not _simply_ an “integer” or “address”. For instance, it’s uncontroversial to say that a Use After Free is clearly Undefined Behavior, even if you “get lucky” and the freed memory gets reallocated before your read/write (in fact this is the worst-case scenario, UAFs would be much less concerning if this didn’t happen!). As another example, consider that [`wrapping_offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_offset "method pointer::wrapping_offset") is documented to “remember” the allocation that the original pointer points to, even if it is offset far outside the memory range occupied by that allocation. To rationalize claims like this, pointers need to somehow be _more_ than just their addresses: they must have **provenance**. A pointer value in Rust semantically contains the following information: * The **address** it points to, which can be represented by a `usize`. * The **provenance** it has, defining the memory it has permission to access. Provenance can be absent, in which case the pointer does not have permission to access any memory. The exact structure of provenance is not yet specified, but the permission defined by a pointer’s provenance have a _spatial_ component, a _temporal_ component, and a _mutability_ component: * Spatial: The set of memory addresses that the pointer is allowed to access. * Temporal: The timespan during which the pointer is allowed to access those memory addresses. * Mutability: Whether the pointer may only access the memory for reads, or also access it for writes. Note that this can interact with the other components, e.g. a pointer might permit mutation only for a subset of addresses, or only for a subset of its maximal timespan. When an [allocation](https://doc.rust-lang.org/stable/std/ptr/index.html#allocation) is created, it has a unique Original Pointer. For alloc APIs this is literally the pointer the call returns, and for local variables and statics, this is the name of the variable/static. (This is mildly overloading the term “pointer” for the sake of brevity/exposition.) The Original Pointer for an allocation has provenance that constrains the _spatial_ permissions of this pointer to the memory range of the allocation, and the _temporal_ permissions to the lifetime of the allocation. Provenance is implicitly inherited by all pointers transitively derived from the Original Pointer through operations like [`offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset "method pointer::offset") , borrowing, and pointer casts. Some operations may _shrink_ the permissions of the derived provenance, limiting how much memory it can access or how long it’s valid for (i.e. borrowing a subfield and subslicing can shrink the spatial component of provenance, and all borrowing can shrink the temporal component of provenance). However, no operation can ever _grow_ the permissions of the derived provenance: even if you “know” there is a larger allocation, you can’t derive a pointer with a larger provenance. Similarly, you cannot “recombine” two contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`). A reference to a place always has provenance over at least the memory that place occupies. A reference to a slice always has provenance over at least the range that slice describes. Whether and when exactly the provenance of a reference gets “shrunk” to _exactly_ fit the memory it points to is not yet determined. A _shared_ reference only ever has provenance that permits reading from memory, and never permits writes, except inside [`UnsafeCell`](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html "struct std::cell::UnsafeCell") . Provenance can affect whether a program has undefined behavior: * It is undefined behavior to access memory through a pointer that does not have provenance over that memory. Note that a pointer “at the end” of its provenance is not actually outside its provenance, it just has 0 bytes it can load/store. Zero-sized accesses do not require any provenance since they access an empty range of memory. * It is undefined behavior to [`offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset "method pointer::offset") a pointer across a memory range that is not contained in the allocation it is derived from, or to [`offset_from`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset_from "method pointer::offset_from") two pointers not derived from the same allocation. Provenance is used to say what exactly “derived from” even means: the lineage of a pointer is traced back to the Original Pointer it descends from, and that identifies the relevant allocation. In particular, it’s always UB to offset a pointer derived from something that is now deallocated, except if the offset is 0. But it _is_ still sound to: * Create a pointer without provenance from just an address (see [`without_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.without_provenance.html "fn std::ptr::without_provenance") ). Such a pointer cannot be used for memory accesses (except for zero-sized accesses). This can still be useful for sentinel values like `null` _or_ to represent a tagged pointer that will never be dereferenceable. In general, it is always sound for an integer to pretend to be a pointer “for fun” as long as you don’t use operations on it which require it to be valid (non-zero-sized offset, read, write, etc). * Forge an allocation of size zero at any sufficiently aligned non-null address. i.e. the usual “ZSTs are fake, do what you want” rules apply. * [`wrapping_offset`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.wrapping_offset "method pointer::wrapping_offset") a pointer outside its provenance. This includes pointers which have “no” provenance. In particular, this makes it sound to do pointer tagging tricks. * Compare arbitrary pointers by address. Pointer comparison ignores provenance and addresses _are_ just integers, so there is always a coherent answer, even if the pointers are dangling or from different provenances. Note that if you get “lucky” and notice that a pointer at the end of one allocation is the “same” address as the start of another allocation, anything you do with that fact is _probably_ going to be gibberish. The scope of that gibberish is kept under control by the fact that the two pointers _still_ aren’t allowed to access the other’s allocation (bytes), because they still have different provenance. Note that the full definition of provenance in Rust is not decided yet, as this interacts with the as-yet undecided [aliasing](https://doc.rust-lang.org/stable/nomicon/aliasing.html) rules. ### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#pointers-vs-integers) Pointers Vs Integers From this discussion, it becomes very clear that a `usize` _cannot_ accurately represent a pointer, and converting from a pointer to a `usize` is generally an operation which _only_ extracts the address. Converting this address back into pointer requires somehow answering the question: which provenance should the resulting pointer have? Rust provides two ways of dealing with this situation: _Strict Provenance_ and _Exposed Provenance_. Note that a pointer _can_ represent a `usize` (via [`without_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.without_provenance.html "fn std::ptr::without_provenance") ), so the right type to use in situations where a value is “sometimes a pointer and sometimes a bare `usize`” is a pointer type. ### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#strict-provenance) Strict Provenance “Strict Provenance” refers to a set of APIs designed to make working with provenance more explicit. They are intended as substitutes for casting a pointer to an integer and back. Entirely avoiding integer-to-pointer casts successfully side-steps the inherent ambiguity of that operation. This benefits compiler optimizations, and it is pretty much a requirement for using tools like [Miri](https://github.com/rust-lang/miri) and architectures like [CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/) that aim to detect and diagnose pointer misuse. The key insight to making programming without integer-to-pointer casts _at all_ viable is the [`with_addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.with_addr "method pointer::with_addr") method: /// Creates a new pointer with the given address. /// /// This performs the same operation as an `addr as ptr` cast, but copies /// the *provenance* of `self` to the new pointer. /// This allows us to dynamically preserve and propagate this important /// information in a way that is otherwise impossible with a unary cast. /// /// This is equivalent to using `wrapping_offset` to offset `self` to the /// given address, and therefore has all the same capabilities and restrictions. pub fn with_addr(self, addr: usize) -> Self; So you’re still able to drop down to the address representation and do whatever clever bit tricks you want _as long as_ you’re able to keep around a pointer into the allocation you care about that can “reconstitute” the provenance. Usually this is very easy, because you only are taking a pointer, messing with the address, and then immediately converting back to a pointer. To make this use case more ergonomic, we provide the [`map_addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.map_addr "method pointer::map_addr") method. To help make it clear that code is “following” Strict Provenance semantics, we also provide an [`addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.addr "method pointer::addr") method which promises that the returned address is not part of a pointer-integer-pointer roundtrip. In the future we may provide a lint for pointer<->integer casts to help you audit if your code conforms to strict provenance. #### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#using-strict-provenance) Using Strict Provenance Most code needs no changes to conform to strict provenance, as the only really concerning operation is casts from `usize` to a pointer. For code which _does_ cast a `usize` to a pointer, the scope of the change depends on exactly what you’re doing. In general, you just need to make sure that if you want to convert a `usize` address to a pointer and then use that pointer to read/write memory, you need to keep around a pointer that has sufficient provenance to perform that read/write itself. In this way all of your casts from an address to a pointer are essentially just applying offsets/indexing. This is generally trivial to do for simple cases like tagged pointers _as long as you represent the tagged pointer as an actual pointer and not a `usize`_. For instance: unsafe { // A flag we want to pack into our pointer static HAS_DATA: usize = 0x1; static FLAG_MASK: usize = !HAS_DATA; // Our value, which must have enough alignment to have spare least-significant-bits. let my_precious_data: u32 = 17; assert!(align_of::() > 1); // Create a tagged pointer let ptr = &my_precious_data as *const u32; let tagged = ptr.map_addr(|addr| addr | HAS_DATA); // Check the flag: if tagged.addr() & HAS_DATA != 0 { // Untag and read the pointer let data = *tagged.map_addr(|addr| addr & FLAG_MASK); assert_eq!(data, 17); } else { unreachable!() } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++unsafe+%7B%0A++++++++//+A+flag+we+want+to+pack+into+our+pointer%0A++++++++static+HAS_DATA:+usize+=+0x1;%0A++++++++static+FLAG_MASK:+usize+=+!HAS_DATA;%0A++++%0A++++++++//+Our+value,+which+must+have+enough+alignment+to+have+spare+least-significant-bits.%0A++++++++let+my_precious_data:+u32+=+17;%0A++++++++assert!(align_of::%3Cu32%3E()+%3E+1);%0A++++%0A++++++++//+Create+a+tagged+pointer%0A++++++++let+ptr+=+%26my_precious_data+as+*const+u32;%0A++++++++let+tagged+=+ptr.map_addr(%7Caddr%7C+addr+%7C+HAS_DATA);%0A++++%0A++++++++//+Check+the+flag:%0A++++++++if+tagged.addr()+%26+HAS_DATA+!=+0+%7B%0A++++++++++++//+Untag+and+read+the+pointer%0A++++++++++++let+data+=+*tagged.map_addr(%7Caddr%7C+addr+%26+FLAG_MASK);%0A++++++++++++assert_eq!(data,+17);%0A++++++++%7D+else+%7B%0A++++++++++++unreachable!()%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") (Yes, if you’ve been using [`AtomicUsize`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html "struct std::sync::atomic::AtomicUsize") for pointers in concurrent datastructures, you should be using [`AtomicPtr`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html "struct std::sync::atomic::AtomicPtr") instead. If that messes up the way you atomically manipulate pointers, we would like to know why, and what needs to be done to fix it.) Situations where a valid pointer _must_ be created from just an address, such as baremetal code accessing a memory-mapped interface at a fixed address, cannot currently be handled with strict provenance APIs and should use [exposed provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#exposed-provenance) . ### [§](https://doc.rust-lang.org/stable/std/ptr/index.html#exposed-provenance) Exposed Provenance As discussed above, integer-to-pointer casts are not possible with Strict Provenance APIs. This is by design: the goal of Strict Provenance is to provide a clear specification that we are confident can be formalized unambiguously and can be subject to precise formal reasoning. Integer-to-pointer casts do not (currently) have such a clear specification. However, there exist situations where integer-to-pointer casts cannot be avoided, or where avoiding them would require major refactoring. Legacy platform APIs also regularly assume that `usize` can capture all the information that makes up a pointer. Bare-metal platforms can also require the synthesis of a pointer “out of thin air” without anywhere to obtain proper provenance from. Rust’s model for dealing with integer-to-pointer casts is called _Exposed Provenance_. However, the semantics of Exposed Provenance are on much less solid footing than Strict Provenance, and at this point it is not yet clear whether a satisfying unambiguous semantics can be defined for Exposed Provenance. (If that sounds bad, be reassured that other popular languages that provide integer-to-pointer casts are not faring any better.) Furthermore, Exposed Provenance will not work (well) with tools like [Miri](https://github.com/rust-lang/miri) and [CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/) . Exposed Provenance is provided by the [`expose_provenance`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.expose_provenance "method pointer::expose_provenance") and [`with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html "fn std::ptr::with_exposed_provenance") methods, which are equivalent to `as` casts between pointers and integers. * [`expose_provenance`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.expose_provenance "method pointer::expose_provenance") is a lot like [`addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.addr "method pointer::addr") , but additionally adds the provenance of the pointer to a global list of ‘exposed’ provenances. (This list is purely conceptual, it exists for the purpose of specifying Rust but is not materialized in actual executions, except in tools like [Miri](https://github.com/rust-lang/miri) .) Memory which is outside the control of the Rust abstract machine (MMIO registers, for example) is always considered to be exposed, so long as this memory is disjoint from memory that will be used by the abstract machine such as the stack, heap, and statics. * [`with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html "fn std::ptr::with_exposed_provenance") can be used to construct a pointer with one of these previously ‘exposed’ provenances. [`with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html "fn std::ptr::with_exposed_provenance") takes only `addr: usize` as arguments, so unlike in [`with_addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.with_addr "method pointer::with_addr") there is no indication of what the correct provenance for the returned pointer is – and that is exactly what makes integer-to-pointer casts so tricky to rigorously specify! The compiler will do its best to pick the right provenance for you, but currently we cannot provide any guarantees about which provenance the resulting pointer will have. Only one thing is clear: if there is _no_ previously ‘exposed’ provenance that justifies the way the returned pointer will be used, the program has undefined behavior. If at all possible, we encourage code to be ported to [Strict Provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#strict-provenance) APIs, thus avoiding the need for Exposed Provenance. Maximizing the amount of such code is a major win for avoiding specification complexity and to facilitate adoption of tools like [CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/) and [Miri](https://github.com/rust-lang/miri) that can be a big help in increasing the confidence in (unsafe) Rust code. However, we acknowledge that this is not always possible, and offer Exposed Provenance as a way to explicit “opt out” of the well-defined semantics of Strict Provenance, and “opt in” to the unclear semantics of integer-to-pointer casts. Macros[§](https://doc.rust-lang.org/stable/std/ptr/index.html#macros) ---------------------------------------------------------------------- [addr\_of](https://doc.rust-lang.org/stable/std/ptr/macro.addr_of.html "macro std::ptr::addr_of") Creates a `const` raw pointer to a place, without creating an intermediate reference. [addr\_of\_mut](https://doc.rust-lang.org/stable/std/ptr/macro.addr_of_mut.html "macro std::ptr::addr_of_mut") Creates a `mut` raw pointer to a place, without creating an intermediate reference. Structs[§](https://doc.rust-lang.org/stable/std/ptr/index.html#structs) ------------------------------------------------------------------------ [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") `*mut T` but non-zero and [covariant](https://doc.rust-lang.org/reference/subtyping.html) . [Alignment](https://doc.rust-lang.org/stable/std/ptr/struct.Alignment.html "struct std::ptr::Alignment") Experimental A type storing a `usize` which is a power of two, and thus represents a possible alignment in the Rust abstract machine. [DynMetadata](https://doc.rust-lang.org/stable/std/ptr/struct.DynMetadata.html "struct std::ptr::DynMetadata") Experimental The metadata for a `Dyn = dyn SomeTrait` trait object type. Traits[§](https://doc.rust-lang.org/stable/std/ptr/index.html#traits) ---------------------------------------------------------------------- [Pointee](https://doc.rust-lang.org/stable/std/ptr/trait.Pointee.html "trait std::ptr::Pointee") Experimental Provides the pointer metadata type of any pointed-to type. Functions[§](https://doc.rust-lang.org/stable/std/ptr/index.html#functions) ---------------------------------------------------------------------------- [addr\_eq](https://doc.rust-lang.org/stable/std/ptr/fn.addr_eq.html "fn std::ptr::addr_eq") Compares the _addresses_ of the two pointers for equality, ignoring any metadata in fat pointers. [copy](https://doc.rust-lang.org/stable/std/ptr/fn.copy.html "fn std::ptr::copy") ⚠ Copies `count * size_of::()` bytes from `src` to `dst`. The source and destination may overlap. [copy\_nonoverlapping](https://doc.rust-lang.org/stable/std/ptr/fn.copy_nonoverlapping.html "fn std::ptr::copy_nonoverlapping") ⚠ Copies `count * size_of::()` bytes from `src` to `dst`. The source and destination must _not_ overlap. [dangling](https://doc.rust-lang.org/stable/std/ptr/fn.dangling.html "fn std::ptr::dangling") Creates a new pointer that is dangling, but non-null and well-aligned. [dangling\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.dangling_mut.html "fn std::ptr::dangling_mut") Creates a new pointer that is dangling, but non-null and well-aligned. [drop\_in\_place](https://doc.rust-lang.org/stable/std/ptr/fn.drop_in_place.html "fn std::ptr::drop_in_place") ⚠ Executes the destructor (if any) of the pointed-to value. [eq](https://doc.rust-lang.org/stable/std/ptr/fn.eq.html "fn std::ptr::eq") Compares raw pointers for equality. [fn\_addr\_eq](https://doc.rust-lang.org/stable/std/ptr/fn.fn_addr_eq.html "fn std::ptr::fn_addr_eq") Compares the _addresses_ of the two function pointers for equality. [from\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.from_mut.html "fn std::ptr::from_mut") Converts a mutable reference to a raw pointer. [from\_ref](https://doc.rust-lang.org/stable/std/ptr/fn.from_ref.html "fn std::ptr::from_ref") Converts a reference to a raw pointer. [hash](https://doc.rust-lang.org/stable/std/ptr/fn.hash.html "fn std::ptr::hash") Hash a raw pointer. [null](https://doc.rust-lang.org/stable/std/ptr/fn.null.html "fn std::ptr::null") Creates a null raw pointer. [null\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.null_mut.html "fn std::ptr::null_mut") Creates a null mutable raw pointer. [read](https://doc.rust-lang.org/stable/std/ptr/fn.read.html "fn std::ptr::read") ⚠ Reads the value from `src` without moving it. This leaves the memory in `src` unchanged. [read\_unaligned](https://doc.rust-lang.org/stable/std/ptr/fn.read_unaligned.html "fn std::ptr::read_unaligned") ⚠ Reads the value from `src` without moving it. This leaves the memory in `src` unchanged. [read\_volatile](https://doc.rust-lang.org/stable/std/ptr/fn.read_volatile.html "fn std::ptr::read_volatile") ⚠ Performs a volatile read of the value from `src` without moving it. [replace](https://doc.rust-lang.org/stable/std/ptr/fn.replace.html "fn std::ptr::replace") ⚠ Moves `src` into the pointed `dst`, returning the previous `dst` value. [slice\_from\_raw\_parts](https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts.html "fn std::ptr::slice_from_raw_parts") Forms a raw slice from a pointer and a length. [slice\_from\_raw\_parts\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts_mut.html "fn std::ptr::slice_from_raw_parts_mut") Forms a raw mutable slice from a pointer and a length. [swap](https://doc.rust-lang.org/stable/std/ptr/fn.swap.html "fn std::ptr::swap") ⚠ Swaps the values at two mutable locations of the same type, without deinitializing either. [swap\_nonoverlapping](https://doc.rust-lang.org/stable/std/ptr/fn.swap_nonoverlapping.html "fn std::ptr::swap_nonoverlapping") ⚠ Swaps `count * size_of::()` bytes between the two regions of memory beginning at `x` and `y`. The two regions must _not_ overlap. [with\_exposed\_provenance](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html "fn std::ptr::with_exposed_provenance") Converts an address back to a pointer, picking up some previously ‘exposed’ [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance "mod std::ptr") . [with\_exposed\_provenance\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance_mut.html "fn std::ptr::with_exposed_provenance_mut") Converts an address back to a mutable pointer, picking up some previously ‘exposed’ [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance "mod std::ptr") . [without\_provenance](https://doc.rust-lang.org/stable/std/ptr/fn.without_provenance.html "fn std::ptr::without_provenance") Creates a pointer with the given address and no [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance "mod std::ptr") . [without\_provenance\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.without_provenance_mut.html "fn std::ptr::without_provenance_mut") Creates a pointer with the given address and no [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance "mod std::ptr") . [write](https://doc.rust-lang.org/stable/std/ptr/fn.write.html "fn std::ptr::write") ⚠ Overwrites a memory location with the given value without reading or dropping the old value. [write\_bytes](https://doc.rust-lang.org/stable/std/ptr/fn.write_bytes.html "fn std::ptr::write_bytes") ⚠ Sets `count * size_of::()` bytes of memory starting at `dst` to `val`. [write\_unaligned](https://doc.rust-lang.org/stable/std/ptr/fn.write_unaligned.html "fn std::ptr::write_unaligned") ⚠ Overwrites a memory location with the given value without reading or dropping the old value. [write\_volatile](https://doc.rust-lang.org/stable/std/ptr/fn.write_volatile.html "fn std::ptr::write_volatile") ⚠ Performs a volatile write of a memory location with the given value without reading or dropping the old value. [from\_raw\_parts](https://doc.rust-lang.org/stable/std/ptr/fn.from_raw_parts.html "fn std::ptr::from_raw_parts") Experimental Forms a (possibly-wide) raw pointer from a data pointer and metadata. [from\_raw\_parts\_mut](https://doc.rust-lang.org/stable/std/ptr/fn.from_raw_parts_mut.html "fn std::ptr::from_raw_parts_mut") Experimental Performs the same functionality as [`from_raw_parts`](https://doc.rust-lang.org/stable/std/ptr/fn.from_raw_parts.html "fn std::ptr::from_raw_parts") , except that a raw `*mut` pointer is returned, as opposed to a raw `*const` pointer. [metadata](https://doc.rust-lang.org/stable/std/ptr/fn.metadata.html "fn std::ptr::metadata") Experimental Extracts the metadata component of a pointer. Trait Aliases[§](https://doc.rust-lang.org/stable/std/ptr/index.html#trait-aliases) ------------------------------------------------------------------------------------ [Thin](https://doc.rust-lang.org/stable/std/ptr/traitalias.Thin.html "traitalias std::ptr::Thin") Experimental Pointers to types implementing this trait alias are “thin”. --- # Future in std::future - Rust [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[future](https://doc.rust-lang.org/stable/std/future/index.html) Trait Future Copy item path =========================== 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#37) pub trait Future { type Output; // Required method fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll; } Expand description A future represents an asynchronous computation, commonly obtained by use of [`async`](https://doc.rust-lang.org/stable/std/keyword.async.html) . A future is a value that might not have finished computing yet. This kind of “asynchronous value” makes it possible for a thread to continue doing useful work while it waits for the value to become available. [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#the-poll-method) The `poll` method ---------------------------------------------------------------------------------------------------- The core method of future, `poll`, _attempts_ to resolve the future into a final value. This method does not block if the value is not ready. Instead, the current task is scheduled to be woken up when it’s possible to make further progress by `poll`ing again. The `context` passed to the `poll` method can provide a [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") , which is a handle for waking up the current task. When using a future, you generally won’t call `poll` directly, but instead `.await` the value. Required Associated Types[§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#required-associated-types) ---------------------------------------------------------------------------------------------------------------------- 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#41) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) The type of value produced on completion. Required Methods[§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#required-methods) ---------------------------------------------------------------------------------------------------- 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#113) #### fn [poll](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll) (self: [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") <&mut Self>, cx: &mut [Context](https://doc.rust-lang.org/stable/std/task/struct.Context.html "struct std::task::Context") <'\_>) -> [Poll](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. ##### [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#return-value) Return value This function returns: * [`Poll::Pending`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html#variant.Pending "variant std::task::Poll::Pending") if the future is not ready yet * [`Poll::Ready(val)`](https://doc.rust-lang.org/stable/std/task/enum.Poll.html#variant.Ready "variant std::task::Poll::Ready") with the result `val` of this future if it finished successfully. Once a future has finished, clients should not `poll` it again. When a future is not ready yet, `poll` returns `Poll::Pending` and stores a clone of the [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") copied from the current [`Context`](https://doc.rust-lang.org/stable/std/task/struct.Context.html "struct std::task::Context") . This [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") is then woken once the future can make progress. For example, a future waiting for a socket to become readable would call `.clone()` on the [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") and store it. When a signal arrives elsewhere indicating that the socket is readable, [`Waker::wake`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html#method.wake "method std::task::Waker::wake") is called and the socket future’s task is awoken. Once a task has been woken up, it should attempt to `poll` the future again, which may or may not produce a final value. Note that on multiple calls to `poll`, only the [`Waker`](https://doc.rust-lang.org/stable/std/task/struct.Waker.html "struct std::task::Waker") from the [`Context`](https://doc.rust-lang.org/stable/std/task/struct.Context.html "struct std::task::Context") passed to the most recent call should be scheduled to receive a wakeup. ##### [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#runtime-characteristics) Runtime characteristics Futures alone are _inert_; they must be _actively_ `poll`ed for the underlying computation to make progress, meaning that each time the current task is woken up, it should actively re-`poll` pending futures that it still has an interest in. Having said that, some Futures may represent a value that is being computed in a different task. In this case, the future’s underlying computation is simply acting as a conduit for a value being computed by that other task, which will proceed independently of the Future. Futures of this kind are typically obtained when spawning a new task into an async runtime. The `poll` function should not be called repeatedly in a tight loop – instead, it should only be called when the future indicates that it is ready to make progress (by calling `wake()`). If you’re familiar with the `poll(2)` or `select(2)` syscalls on Unix it’s worth noting that futures typically do _not_ suffer the same problems of “all wakeups must poll all events”; they are more like `epoll(4)`. An implementation of `poll` should strive to return quickly, and should not block. Returning quickly prevents unnecessarily clogging up threads or event loops. If it is known ahead of time that a call to `poll` may end up taking a while, the work should be offloaded to a thread pool (or something similar) to ensure that `poll` can return quickly. ##### [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#panics) Panics Once a future has completed (returned `Ready` from `poll`), calling its `poll` method again may panic, block forever, or cause other kinds of problems; the `Future` trait places no requirements on the effects of such a call. However, as the `poll` method is not marked `unsafe`, Rust’s usual rules apply: calls must never cause undefined behavior (memory corruption, incorrect use of `unsafe` functions, or the like), regardless of the future’s state. Implementors[§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#implementors) -------------------------------------------------------------------------------------------- 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#117) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-%26mut+F) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [&mut F](https://doc.rust-lang.org/stable/std/primitive.reference.html) where F: [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") + [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#118) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-1) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = ::[Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output "type std::future::Future::Output") 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/panic/unwind_safe.rs.html#293) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-AssertUnwindSafe%3CF%3E) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [AssertUnwindSafe](https://doc.rust-lang.org/stable/std/panic/struct.AssertUnwindSafe.html "struct std::panic::AssertUnwindSafe") where F: [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") , [Source](https://doc.rust-lang.org/stable/src/core/panic/unwind_safe.rs.html#294) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-2) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = ::[Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output "type std::future::Future::Output") 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed.rs.html#2141) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-Box%3CF,+A%3E) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where F: [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") + [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/boxed.rs.html#2142) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-3) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = ::[Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output "type std::future::Future::Output") 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#126-128) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-Pin%3CP%3E) ### impl

[Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin")

where P: [DerefMut](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "trait std::ops::DerefMut") ,

::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "type std::ops::Deref::Target") : [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") , [Source](https://doc.rust-lang.org/stable/src/core/future/future.rs.html#130) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-4) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = <

`. For that reason, it’s relatively rare to need to implement this directly. You’ll typically do this only if you need to implement a smart pointer type which can’t implement [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") ; perhaps because you’re interfacing with another programming language and can’t guarantee that references comply with Rust’s aliasing rules. When looking for method candidates, Rust will explore a chain of possible `Receiver`s, so for example each of the following methods work: use std::boxed::Box; use std::rc::Rc; // Both `Box` and `Rc` (indirectly) implement Receiver struct MyContainedType; fn main() { let t = Rc::new(Box::new(MyContainedType)); t.method_a(); t.method_b(); t.method_c(); } impl MyContainedType { fn method_a(&self) { } fn method_b(self: &Box) { } fn method_c(self: &Rc>) { } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::boxed::Box;%0Ause+std::rc::Rc;%0A%0A//+Both+%60Box%60+and+%60Rc%60+(indirectly)+implement+Receiver%0A%0Astruct+MyContainedType;%0A%0Afn+main()+%7B%0A++let+t+=+Rc::new(Box::new(MyContainedType));%0A++t.method_a();%0A++t.method_b();%0A++t.method_c();%0A%7D%0A%0Aimpl+MyContainedType+%7B%0A++fn+method_a(%26self)+%7B%0A%0A++%7D%0A++fn+method_b(self:+%26Box%3CSelf%3E)+%7B%0A%0A++%7D%0A++fn+method_c(self:+%26Rc%3CBox%3CSelf%3E%3E)+%7B%0A%0A++%7D%0A%7D&edition=2024 "Run code") Required Associated Types[§](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#required-associated-types) --------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#374) #### type [Target](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#associatedtype.Target) : ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") 🔬This is a nightly-only experimental API. (`arbitrary_self_types` [#44874](https://github.com/rust-lang/rust/issues/44874) ) The target type on which the method may be called. Implementors[§](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#implementors) ------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#378-380) [§](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#impl-Receiver-for-P) ### impl [Receiver](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html "trait std::ops::Receiver") for P where P: [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#382) [§](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#associatedtype.Target-1) #### type [Target](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#associatedtype.Target) = T --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m128.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m128.html) ... --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m128d.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m128d.html) ... --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m256.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m256.html) ... --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m256bh.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m256bh.html) ... --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m128i.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m128i.html) ... --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m128bh.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m128bh.html) ... --- # ToString in std::string - Rust [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[string](https://doc.rust-lang.org/stable/std/string/index.html) Trait ToString Copy item path ============================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2841) pub trait ToString { // Required method fn to_string(&self) -> String; } Expand description A trait for converting a value to a `String`. This trait is automatically implemented for any type which implements the [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") trait. As such, `ToString` shouldn’t be implemented directly: [`Display`](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") should be implemented instead, and you get the `ToString` implementation for free. Required Methods[§](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#required-methods) ------------------------------------------------------------------------------------------------------ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2855) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. ##### [§](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#examples) Examples let i = 5; let five = String::from("5"); assert_eq!(five, i.to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+i+=+5;%0A++++let+five+=+String::from(%225%22);%0A++++%0A++++assert_eq!(five,+i.to_string());%0A%7D&edition=2024 "Run code") Implementors[§](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#implementors) ---------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , #### [§](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#panics) Panics In this implementation, the `to_string` method panics if the `Display` implementation returns an error. This indicates an incorrect `Display` implementation since `fmt::Write for String` never returns an error itself. --- # Into in std::convert - Rust [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#) ---------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[convert](https://doc.rust-lang.org/stable/std/convert/index.html) Trait Into Copy item path ========================= 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#451) pub trait Into: Sized { // Required method fn into(self) -> T; } Expand description A value-to-value conversion that consumes the input value. The opposite of [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") . One should avoid implementing [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") and implement [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") instead. Implementing [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") automatically provides one with an implementation of [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") thanks to the blanket implementation in the standard library. Prefer using [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") over [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") when specifying trait bounds on a generic function to ensure that types that only implement [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") can be used as well. **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") . [§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#generic-implementations) Generic Implementations ----------------------------------------------------------------------------------------------------------------- * [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") ` for U` implies `Into for T` * [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") is reflexive, which means that `Into for T` is implemented [§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#implementing-into-for-conversions-to-external-types-in-old-versions-of-rust) Implementing [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for conversions to external types in old versions of Rust ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Prior to Rust 1.41, if the destination type was not part of the current crate then you couldn’t implement [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") directly. For example, take this code: struct Wrapper(Vec); impl From> for Vec { fn from(w: Wrapper) -> Vec { w.0 } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Ballow(non_local_definitions)%5D%0A%0Afn+main()+%7B%0A++++struct+Wrapper%3CT%3E(Vec%3CT%3E);%0A++++impl%3CT%3E+From%3CWrapper%3CT%3E%3E+for+Vec%3CT%3E+%7B%0A++++++++fn+from(w:+Wrapper%3CT%3E)+-%3E+Vec%3CT%3E+%7B%0A++++++++++++w.0%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") This will fail to compile in older versions of the language because Rust’s orphaning rules used to be a little bit more strict. To bypass this, you could implement [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") directly: struct Wrapper(Vec); impl Into> for Wrapper { fn into(self) -> Vec { self.0 } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++struct+Wrapper%3CT%3E(Vec%3CT%3E);%0A++++impl%3CT%3E+Into%3CVec%3CT%3E%3E+for+Wrapper%3CT%3E+%7B%0A++++++++fn+into(self)+-%3E+Vec%3CT%3E+%7B%0A++++++++++++self.0%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") It is important to understand that [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") does not provide a [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") implementation (as [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") does with [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") ). Therefore, you should always try to implement [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") and then fall back to [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") if [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") can’t be implemented. [§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#examples) Examples ----------------------------------------------------------------------------------- [`String`](https://doc.rust-lang.org/stable/std/string/struct.String.html) implements [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") `<`[`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) `<`[`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") `>>`: In order to express that we want a generic function to take all arguments that can be converted to a specified type `T`, we can use a trait bound of [`Into`](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") ``. For example: The function `is_hello` takes all arguments that can be converted into a [`Vec`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html) `<`[`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html "primitive u8") `>`. fn is_hello>>(s: T) { let bytes = b"hello".to_vec(); assert_eq!(bytes, s.into()); } let s = "hello".to_string(); is_hello(s); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+is_hello%3CT:+Into%3CVec%3Cu8%3E%3E%3E(s:+T)+%7B%0A+++++++let+bytes+=+b%22hello%22.to_vec();%0A+++++++assert_eq!(bytes,+s.into());%0A++++%7D%0A++++%0A++++let+s+=+%22hello%22.to_string();%0A++++is_hello(s);%0A%7D&edition=2024 "Run code") Required Methods[§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#required-methods) --------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#455) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> T Converts this type into the (usually inferred) input type. Dyn Compatibility[§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#dyn-compatibility) ----------------------------------------------------------------------------------------------------- This trait is **not** [dyn compatible](https://doc.rust-lang.org/1.92.0/reference/items/traits.html#dyn-compatibility) . _In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe._ Implementors[§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#implementors) ------------------------------------------------------------------------------------------- 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , --- # Any in std::any - Rust [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html#) ---------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[any](https://doc.rust-lang.org/stable/std/any/index.html) Trait Any Copy item path ======================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#113) pub trait Any: 'static { // Required method fn type_id(&self) -> TypeId; } Expand description A trait to emulate dynamic typing. Most types implement `Any`. However, any type which contains a non-`'static` reference does not. See the [module-level documentation](https://doc.rust-lang.org/stable/std/any/index.html "mod std::any") for more details. Required Methods[§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#required-methods) ---------------------------------------------------------------------------------------------- 1.34.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#134) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. If called on a `dyn Any` trait object (or a trait object of a subtrait of `Any`), this returns the `TypeId` of the underlying concrete type, not that of `dyn Any` itself. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples) Examples use std::any::{Any, TypeId}; fn is_string(s: &dyn Any) -> bool { TypeId::of::() == s.type_id() } assert_eq!(is_string(&0), false); assert_eq!(is_string(&"cookie monster".to_string()), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::%7BAny,+TypeId%7D;%0A++++%0A++++fn+is_string(s:+%26dyn+Any)+-%3E+bool+%7B%0A++++++++TypeId::of::%3CString%3E()+==+s.type_id()%0A++++%7D%0A++++%0A++++assert_eq!(is_string(%260),+false);%0A++++assert_eq!(is_string(%26%22cookie+monster%22.to_string()),+true);%0A%7D&edition=2024 "Run code") Implementations[§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#implementations) -------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#172) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-dyn+Any) ### impl dyn [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#193) #### pub fn [is](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.is) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Returns `true` if the inner type is the same as `T`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-1) Examples use std::any::Any; fn is_string(s: &dyn Any) { if s.is::() { println!("It's a string!"); } else { println!("Not a string..."); } } is_string(&0); is_string(&"cookie monster".to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+is_string(s:+%26dyn+Any)+%7B%0A++++++++if+s.is::%3CString%3E()+%7B%0A++++++++++++println!(%22It%27s+a+string!%22);%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22Not+a+string...%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++is_string(%260);%0A++++is_string(%26%22cookie+monster%22.to_string());%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#225) #### pub fn [downcast\_ref](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_ref) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Returns some reference to the inner value if it is of type `T`, or `None` if it isn’t. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-2) Examples use std::any::Any; fn print_if_string(s: &dyn Any) { if let Some(string) = s.downcast_ref::() { println!("It's a string({}): '{}'", string.len(), string); } else { println!("Not a string..."); } } print_if_string(&0); print_if_string(&"cookie monster".to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+print_if_string(s:+%26dyn+Any)+%7B%0A++++++++if+let+Some(string)+=+s.downcast_ref::%3CString%3E()+%7B%0A++++++++++++println!(%22It%27s+a+string(%7B%7D):+%27%7B%7D%27%22,+string.len(),+string);%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22Not+a+string...%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++print_if_string(%260);%0A++++print_if_string(%26%22cookie+monster%22.to_string());%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#261) #### pub fn [downcast\_mut](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_mut) (&mut self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Returns some mutable reference to the inner value if it is of type `T`, or `None` if it isn’t. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-3) Examples use std::any::Any; fn modify_if_u32(s: &mut dyn Any) { if let Some(num) = s.downcast_mut::() { *num = 42; } } let mut x = 10u32; let mut s = "starlord".to_string(); modify_if_u32(&mut x); modify_if_u32(&mut s); assert_eq!(x, 42); assert_eq!(&s, "starlord"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+modify_if_u32(s:+%26mut+dyn+Any)+%7B%0A++++++++if+let+Some(num)+=+s.downcast_mut::%3Cu32%3E()+%7B%0A++++++++++++*num+=+42;%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+mut+x+=+10u32;%0A++++let+mut+s+=+%22starlord%22.to_string();%0A++++%0A++++modify_if_u32(%26mut+x);%0A++++modify_if_u32(%26mut+s);%0A++++%0A++++assert_eq!(x,+42);%0A++++assert_eq!(%26s,+%22starlord%22);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#294) #### pub unsafe fn [downcast\_ref\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_ref_unchecked) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Returns a reference to the inner value as type `dyn T`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-4) Examples #![feature(downcast_unchecked)] use std::any::Any; let x: Box = Box::new(1_usize); unsafe { assert_eq!(*x.downcast_ref_unchecked::(), 1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++assert_eq!(*x.downcast_ref_unchecked::%3Cusize%3E(),+1);%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#324) #### pub unsafe fn [downcast\_mut\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_mut_unchecked) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Returns a mutable reference to the inner value as type `dyn T`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-5) Examples #![feature(downcast_unchecked)] use std::any::Any; let mut x: Box = Box::new(1_usize); unsafe { *x.downcast_mut_unchecked::() += 1; } assert_eq!(*x.downcast_ref::().unwrap(), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+mut+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++*x.downcast_mut_unchecked::%3Cusize%3E()+%2B=+1;%0A++++%7D%0A++++%0A++++assert_eq!(*x.downcast_ref::%3Cusize%3E().unwrap(),+2);%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-1) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#331) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-dyn+Any+%2B+Send) ### impl dyn [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") + [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#352) #### pub fn [is](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.is-1) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Forwards to the method defined on the type `dyn Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-6) Examples use std::any::Any; fn is_string(s: &(dyn Any + Send)) { if s.is::() { println!("It's a string!"); } else { println!("Not a string..."); } } is_string(&0); is_string(&"cookie monster".to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+is_string(s:+%26(dyn+Any+%2B+Send))+%7B%0A++++++++if+s.is::%3CString%3E()+%7B%0A++++++++++++println!(%22It%27s+a+string!%22);%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22Not+a+string...%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++is_string(%260);%0A++++is_string(%26%22cookie+monster%22.to_string());%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#376) #### pub fn [downcast\_ref](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_ref-1) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Forwards to the method defined on the type `dyn Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-7) Examples use std::any::Any; fn print_if_string(s: &(dyn Any + Send)) { if let Some(string) = s.downcast_ref::() { println!("It's a string({}): '{}'", string.len(), string); } else { println!("Not a string..."); } } print_if_string(&0); print_if_string(&"cookie monster".to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+print_if_string(s:+%26(dyn+Any+%2B+Send))+%7B%0A++++++++if+let+Some(string)+=+s.downcast_ref::%3CString%3E()+%7B%0A++++++++++++println!(%22It%27s+a+string(%7B%7D):+%27%7B%7D%27%22,+string.len(),+string);%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22Not+a+string...%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++print_if_string(%260);%0A++++print_if_string(%26%22cookie+monster%22.to_string());%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#404) #### pub fn [downcast\_mut](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_mut-1) (&mut self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Forwards to the method defined on the type `dyn Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-8) Examples use std::any::Any; fn modify_if_u32(s: &mut (dyn Any + Send)) { if let Some(num) = s.downcast_mut::() { *num = 42; } } let mut x = 10u32; let mut s = "starlord".to_string(); modify_if_u32(&mut x); modify_if_u32(&mut s); assert_eq!(x, 42); assert_eq!(&s, "starlord"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+modify_if_u32(s:+%26mut+(dyn+Any+%2B+Send))+%7B%0A++++++++if+let+Some(num)+=+s.downcast_mut::%3Cu32%3E()+%7B%0A++++++++++++*num+=+42;%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+mut+x+=+10u32;%0A++++let+mut+s+=+%22starlord%22.to_string();%0A++++%0A++++modify_if_u32(%26mut+x);%0A++++modify_if_u32(%26mut+s);%0A++++%0A++++assert_eq!(x,+42);%0A++++assert_eq!(%26s,+%22starlord%22);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#430) #### pub unsafe fn [downcast\_ref\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_ref_unchecked-1) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Forwards to the method defined on the type `dyn Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-9) Examples #![feature(downcast_unchecked)] use std::any::Any; let x: Box = Box::new(1_usize); unsafe { assert_eq!(*x.downcast_ref_unchecked::(), 1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++assert_eq!(*x.downcast_ref_unchecked::%3Cusize%3E(),+1);%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-2) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#459) #### pub unsafe fn [downcast\_mut\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_mut_unchecked-1) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Forwards to the method defined on the type `dyn Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-10) Examples #![feature(downcast_unchecked)] use std::any::Any; let mut x: Box = Box::new(1_usize); unsafe { *x.downcast_mut_unchecked::() += 1; } assert_eq!(*x.downcast_ref::().unwrap(), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+mut+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++*x.downcast_mut_unchecked::%3Cusize%3E()+%2B=+1;%0A++++%7D%0A++++%0A++++assert_eq!(*x.downcast_ref::%3Cusize%3E().unwrap(),+2);%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-3) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#465) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-dyn+Any+%2B+Send+%2B+Sync) ### impl dyn [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") + [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") + [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#486) #### pub fn [is](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.is-2) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Forwards to the method defined on the type `Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-11) Examples use std::any::Any; fn is_string(s: &(dyn Any + Send + Sync)) { if s.is::() { println!("It's a string!"); } else { println!("Not a string..."); } } is_string(&0); is_string(&"cookie monster".to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+is_string(s:+%26(dyn+Any+%2B+Send+%2B+Sync))+%7B%0A++++++++if+s.is::%3CString%3E()+%7B%0A++++++++++++println!(%22It%27s+a+string!%22);%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22Not+a+string...%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++is_string(%260);%0A++++is_string(%26%22cookie+monster%22.to_string());%0A%7D&edition=2024 "Run code") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#510) #### pub fn [downcast\_ref](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_ref-2) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Forwards to the method defined on the type `Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-12) Examples use std::any::Any; fn print_if_string(s: &(dyn Any + Send + Sync)) { if let Some(string) = s.downcast_ref::() { println!("It's a string({}): '{}'", string.len(), string); } else { println!("Not a string..."); } } print_if_string(&0); print_if_string(&"cookie monster".to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+print_if_string(s:+%26(dyn+Any+%2B+Send+%2B+Sync))+%7B%0A++++++++if+let+Some(string)+=+s.downcast_ref::%3CString%3E()+%7B%0A++++++++++++println!(%22It%27s+a+string(%7B%7D):+%27%7B%7D%27%22,+string.len(),+string);%0A++++++++%7D+else+%7B%0A++++++++++++println!(%22Not+a+string...%22);%0A++++++++%7D%0A++++%7D%0A++++%0A++++print_if_string(%260);%0A++++print_if_string(%26%22cookie+monster%22.to_string());%0A%7D&edition=2024 "Run code") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#538) #### pub fn [downcast\_mut](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_mut-2) (&mut self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Forwards to the method defined on the type `Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-13) Examples use std::any::Any; fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) { if let Some(num) = s.downcast_mut::() { *num = 42; } } let mut x = 10u32; let mut s = "starlord".to_string(); modify_if_u32(&mut x); modify_if_u32(&mut s); assert_eq!(x, 42); assert_eq!(&s, "starlord"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+modify_if_u32(s:+%26mut+(dyn+Any+%2B+Send+%2B+Sync))+%7B%0A++++++++if+let+Some(num)+=+s.downcast_mut::%3Cu32%3E()+%7B%0A++++++++++++*num+=+42;%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+mut+x+=+10u32;%0A++++let+mut+s+=+%22starlord%22.to_string();%0A++++%0A++++modify_if_u32(%26mut+x);%0A++++modify_if_u32(%26mut+s);%0A++++%0A++++assert_eq!(x,+42);%0A++++assert_eq!(%26s,+%22starlord%22);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#563) #### pub unsafe fn [downcast\_ref\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_ref_unchecked-2) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Forwards to the method defined on the type `Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-14) Examples #![feature(downcast_unchecked)] use std::any::Any; let x: Box = Box::new(1_usize); unsafe { assert_eq!(*x.downcast_ref_unchecked::(), 1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++assert_eq!(*x.downcast_ref_unchecked::%3Cusize%3E(),+1);%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-4) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#591) #### pub unsafe fn [downcast\_mut\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_mut_unchecked-2) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Forwards to the method defined on the type `Any`. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-15) Examples #![feature(downcast_unchecked)] use std::any::Any; let mut x: Box = Box::new(1_usize); unsafe { *x.downcast_mut_unchecked::() += 1; } assert_eq!(*x.downcast_ref::().unwrap(), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+mut+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++*x.downcast_mut_unchecked::%3Cusize%3E()+%2B=+1;%0A++++%7D%0A++++%0A++++assert_eq!(*x.downcast_ref::%3Cusize%3E().unwrap(),+2);%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-5) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#344) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Box%3Cdyn+Any,+A%3E) ### impl [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#364) #### pub fn [downcast](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") , [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") > where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Attempts to downcast the box to a concrete type. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-16) Examples use std::any::Any; fn print_if_string(value: Box) { if let Ok(string) = value.downcast::() { println!("String ({}): {}", string.len(), string); } } let my_string = "Hello World".to_string(); print_if_string(Box::new(my_string)); print_if_string(Box::new(0i8)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+print_if_string(value:+Box%3Cdyn+Any%3E)+%7B%0A++++++++if+let+Ok(string)+=+value.downcast::%3CString%3E()+%7B%0A++++++++++++println!(%22String+(%7B%7D):+%7B%7D%22,+string.len(),+string);%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+my_string+=+%22Hello+World%22.to_string();%0A++++print_if_string(Box::new(my_string));%0A++++print_if_string(Box::new(0i8));%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#394) #### pub unsafe fn [downcast\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_unchecked) (self) -> [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Downcasts the box to a concrete type. For a safe alternative see [`downcast`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.downcast "method std::boxed::Box::downcast") . ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-17) Examples #![feature(downcast_unchecked)] use std::any::Any; let x: Box = Box::new(1_usize); unsafe { assert_eq!(*x.downcast_unchecked::(), 1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+x:+Box%3Cdyn+Any%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++assert_eq!(*x.downcast_unchecked::%3Cusize%3E(),+1);%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-6) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#403) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Box%3Cdyn+Any+%2B+Send,+A%3E) ### impl [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#423) #### pub fn [downcast](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast-1) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") , [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") > where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Attempts to downcast the box to a concrete type. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-18) Examples use std::any::Any; fn print_if_string(value: Box) { if let Ok(string) = value.downcast::() { println!("String ({}): {}", string.len(), string); } } let my_string = "Hello World".to_string(); print_if_string(Box::new(my_string)); print_if_string(Box::new(0i8)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+print_if_string(value:+Box%3Cdyn+Any+%2B+Send%3E)+%7B%0A++++++++if+let+Ok(string)+=+value.downcast::%3CString%3E()+%7B%0A++++++++++++println!(%22String+(%7B%7D):+%7B%7D%22,+string.len(),+string);%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+my_string+=+%22Hello+World%22.to_string();%0A++++print_if_string(Box::new(my_string));%0A++++print_if_string(Box::new(0i8));%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#453) #### pub unsafe fn [downcast\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_unchecked-1) (self) -> [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Downcasts the box to a concrete type. For a safe alternative see [`downcast`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.downcast "method std::boxed::Box::downcast") . ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-19) Examples #![feature(downcast_unchecked)] use std::any::Any; let x: Box = Box::new(1_usize); unsafe { assert_eq!(*x.downcast_unchecked::(), 1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+x:+Box%3Cdyn+Any+%2B+Send%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++assert_eq!(*x.downcast_unchecked::%3Cusize%3E(),+1);%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-7) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#462) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Box%3Cdyn+Any+%2B+Send+%2B+Sync,+A%3E) ### impl [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.51.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#482) #### pub fn [downcast](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast-2) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") , [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") > where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , Attempts to downcast the box to a concrete type. ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-20) Examples use std::any::Any; fn print_if_string(value: Box) { if let Ok(string) = value.downcast::() { println!("String ({}): {}", string.len(), string); } } let my_string = "Hello World".to_string(); print_if_string(Box::new(my_string)); print_if_string(Box::new(0i8)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++fn+print_if_string(value:+Box%3Cdyn+Any+%2B+Send+%2B+Sync%3E)+%7B%0A++++++++if+let+Ok(string)+=+value.downcast::%3CString%3E()+%7B%0A++++++++++++println!(%22String+(%7B%7D):+%7B%7D%22,+string.len(),+string);%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+my_string+=+%22Hello+World%22.to_string();%0A++++print_if_string(Box::new(my_string));%0A++++print_if_string(Box::new(0i8));%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/boxed/convert.rs.html#512) #### pub unsafe fn [downcast\_unchecked](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.downcast_unchecked-2) (self) -> [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where T: [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") , 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850) ) Downcasts the box to a concrete type. For a safe alternative see [`downcast`](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.downcast "method std::boxed::Box::downcast") . ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#examples-21) Examples #![feature(downcast_unchecked)] use std::any::Any; let x: Box = Box::new(1_usize); unsafe { assert_eq!(*x.downcast_unchecked::(), 1); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(downcast_unchecked)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::any::Any;%0A++++%0A++++let+x:+Box%3Cdyn+Any+%2B+Send+%2B+Sync%3E+=+Box::new(1_usize);%0A++++%0A++++unsafe+%7B%0A++++++++assert_eq!(*x.downcast_unchecked::%3Cusize%3E(),+1);%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#safety-8) Safety The contained value must be of type `T`. Calling this method with the incorrect type is _undefined behavior_. Trait Implementations[§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#trait-implementations) -------------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#149) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Debug-for-dyn+Any) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for dyn [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#150) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#159) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Debug-for-dyn+Any+%2B+Send) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for dyn [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") + [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#160) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#166) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Debug-for-dyn+Any+%2B+Send+%2B+Sync) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for dyn [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") + [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") + [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#167) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#method.fmt-2) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) Implementors[§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#implementors) -------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/any/trait.Any.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , --- # DerefPure in std::ops - Rust [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#) ---------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[ops](https://doc.rust-lang.org/stable/std/ops/index.html) Trait DerefPure Copy item path ============================== [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#296) pub unsafe trait DerefPure { } 🔬This is a nightly-only experimental API. (`deref_pure_trait` [#87121](https://github.com/rust-lang/rust/issues/87121) ) Expand description Perma-unstable marker trait. Indicates that the type has a well-behaved [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") (and, if applicable, [`DerefMut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "trait std::ops::DerefMut") ) implementation. This is relied on for soundness of deref patterns. FIXME(deref\_patterns): The precise semantics are undecided; the rough idea is that successive calls to `deref`/`deref_mut` without intermediate mutation should be idempotent, in the sense that they return the same value as far as pattern-matching is concerned. Calls to `deref`/`deref_mut` must leave the pointer itself likewise unchanged. Implementors[§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#implementors) -------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#357) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Cow%3C'_,+str%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> [Source](https://doc.rust-lang.org/stable/src/core/bstr/mod.rs.html#129) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-ByteStr) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#85) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-ByteString) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2803) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-String) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") [Source](https://doc.rust-lang.org/stable/src/core/pin.rs.html#1781) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Pin%3CPtr%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") where Ptr: [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#360) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Cow%3C'_,+%5BT%5D%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, [\[T\]](https://doc.rust-lang.org/stable/std/primitive.slice.html) \> where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#354) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Cow%3C'_,+T%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, T> where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#299) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-%26T) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#302) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-%26mut+T) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#1601) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Ref%3C'_,+T%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Ref](https://doc.rust-lang.org/stable/std/cell/struct.Ref.html "struct std::cell::Ref") <'\_, T> where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#2095) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-RefMut%3C'_,+T%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [RefMut](https://doc.rust-lang.org/stable/std/cell/struct.RefMut.html "struct std::cell::RefMut") <'\_, T> where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/mem/manually_drop.rs.html#285) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-ManuallyDrop%3CT%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [ManuallyDrop](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "struct std::mem::ManuallyDrop") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/boxed.rs.html#1995) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Box%3CT,+A%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#2256) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Rc%3CT,+A%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Rc](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#2260) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-UniqueRc%3CT,+A%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [UniqueRc](https://doc.rust-lang.org/stable/std/rc/struct.UniqueRc.html "struct std::rc::UniqueRc") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#2243) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Arc%3CT,+A%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Arc](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#4518) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-UniqueArc%3CT,+A%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [UniqueArc](https://doc.rust-lang.org/stable/std/sync/struct.UniqueArc.html "struct std::sync::UniqueArc") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/vec/mod.rs.html#3566) [§](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html#impl-DerefPure-for-Vec%3CT,+A%3E) ### impl [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") for [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , --- # CloneToUninit in std::clone - Rust [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#) -------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[clone](https://doc.rust-lang.org/stable/std/clone/index.html) Trait CloneToUninit Copy item path ================================== [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#475) pub unsafe trait CloneToUninit { // Required method unsafe fn clone_to_uninit(&self, dest: *mut u8); } 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Expand description A generalization of [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") to [dynamically-sized types](https://doc.rust-lang.org/reference/dynamically-sized-types.html) stored in arbitrary containers. This trait is implemented for all types implementing [`Clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [slices](https://doc.rust-lang.org/stable/std/primitive.slice.html "primitive slice") of all such types, and other dynamically-sized types in the standard library. You may also implement this trait to enable cloning custom DSTs (structures containing dynamically-sized fields), or use it as a supertrait to enable cloning a [trait object](https://doc.rust-lang.org/reference/types/trait-object.html) . This trait is normally used via operations on container types which support DSTs, so you should not typically need to call `.clone_to_uninit()` explicitly except when implementing such a container or otherwise performing explicit management of an allocation, or when implementing `CloneToUninit` itself. [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#safety) Safety -------------------------------------------------------------------------------------- Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than panicking, it always leaves `*dest` initialized as a valid value of type `Self`. [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#examples) Examples ------------------------------------------------------------------------------------------ If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of `dyn` values of your trait: #![feature(clone_to_uninit)] use std::rc::Rc; trait Foo: std::fmt::Debug + std::clone::CloneToUninit { fn modify(&mut self); fn value(&self) -> i32; } impl Foo for i32 { fn modify(&mut self) { *self *= 10; } fn value(&self) -> i32 { *self } } let first: Rc = Rc::new(1234); let mut second = first.clone(); Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit() assert_eq!(first.value(), 1234); assert_eq!(second.value(), 12340); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(clone_to_uninit)%5D%0A%0Afn+main()+%7B%0A++++use+std::rc::Rc;%0A++++%0A++++trait+Foo:+std::fmt::Debug+%2B+std::clone::CloneToUninit+%7B%0A++++++++fn+modify(%26mut+self);%0A++++++++fn+value(%26self)+-%3E+i32;%0A++++%7D%0A++++%0A++++impl+Foo+for+i32+%7B%0A++++++++fn+modify(%26mut+self)+%7B%0A++++++++++++*self+*=+10;%0A++++++++%7D%0A++++++++fn+value(%26self)+-%3E+i32+%7B%0A++++++++++++*self%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+first:+Rc%3Cdyn+Foo%3E+=+Rc::new(1234);%0A++++%0A++++let+mut+second+=+first.clone();%0A++++Rc::make_mut(%26mut+second).modify();+//+make_mut()+will+call+clone_to_uninit()%0A++++%0A++++assert_eq!(first.value(),+1234);%0A++++assert_eq!(second.value(),+12340);%0A%7D&version=nightly&edition=2024 "Run code") The following is an example of implementing `CloneToUninit` for a custom DST. (It is essentially a limited form of what `derive(CloneToUninit)` would do, if such a derive macro existed.) #![feature(clone_to_uninit)] use std::clone::CloneToUninit; use std::mem::offset_of; use std::rc::Rc; #[derive(PartialEq)] struct MyDst { label: String, contents: T, } unsafe impl CloneToUninit for MyDst { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // The offset of `self.contents` is dynamic because it depends on the alignment of T // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it // dynamically by examining `self`, rather than using `offset_of!`. // // SAFETY: `self` by definition points somewhere before `&self.contents` in the same // allocation. let offset_of_contents = unsafe { (&raw const self.contents).byte_offset_from_unsigned(self) }; // Clone the *sized* fields of `self` (just one, in this example). // (By cloning this first and storing it temporarily in a local variable, we avoid // leaking it in case of any panic, using the ordinary automatic cleanup of local // variables. Such a leak would be sound, but undesirable.) let label = self.label.clone(); // SAFETY: The caller must provide a `dest` such that these field offsets are valid // to write to. unsafe { // Clone the unsized field directly from `self` to `dest`. self.contents.clone_to_uninit(dest.add(offset_of_contents)); // Now write all the sized fields. // // Note that we only do this once all of the clone() and clone_to_uninit() calls // have completed, and therefore we know that there are no more possible panics; // this ensures no memory leaks in case of panic. dest.add(offset_of!(Self, label)).cast::().write(label); } // All fields of the struct have been initialized; therefore, the struct is initialized, // and we have satisfied our `unsafe impl CloneToUninit` obligations. } } fn main() { // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>. let first: Rc> = Rc::new(MyDst { label: String::from("hello"), contents: [1, 2, 3, 4], }); let mut second = first.clone(); // make_mut() will call clone_to_uninit(). for elem in Rc::make_mut(&mut second).contents.iter_mut() { *elem *= 10; } assert_eq!(first.contents, [1, 2, 3, 4]); assert_eq!(second.contents, [10, 20, 30, 40]); assert_eq!(second.label, "hello"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(clone_to_uninit)%5D%0A%0Ause+std::clone::CloneToUninit;%0Ause+std::mem::offset_of;%0Ause+std::rc::Rc;%0A%0A%23%5Bderive(PartialEq)%5D%0Astruct+MyDst%3CT:+?Sized%3E+%7B%0A++++label:+String,%0A++++contents:+T,%0A%7D%0A%0Aunsafe+impl%3CT:+?Sized+%2B+CloneToUninit%3E+CloneToUninit+for+MyDst%3CT%3E+%7B%0A++++unsafe+fn+clone_to_uninit(%26self,+dest:+*mut+u8)+%7B%0A++++++++//+The+offset+of+%60self.contents%60+is+dynamic+because+it+depends+on+the+alignment+of+T%0A++++++++//+which+can+be+dynamic+(if+%60T+=+dyn+SomeTrait%60).+Therefore,+we+have+to+obtain+it%0A++++++++//+dynamically+by+examining+%60self%60,+rather+than+using+%60offset_of!%60.%0A++++++++//%0A++++++++//+SAFETY:+%60self%60+by+definition+points+somewhere+before+%60%26self.contents%60+in+the+same%0A++++++++//+allocation.%0A++++++++let+offset_of_contents+=+unsafe+%7B%0A++++++++++++(%26raw+const+self.contents).byte_offset_from_unsigned(self)%0A++++++++%7D;%0A%0A++++++++//+Clone+the+*sized*+fields+of+%60self%60+(just+one,+in+this+example).%0A++++++++//+(By+cloning+this+first+and+storing+it+temporarily+in+a+local+variable,+we+avoid%0A++++++++//+leaking+it+in+case+of+any+panic,+using+the+ordinary+automatic+cleanup+of+local%0A++++++++//+variables.+Such+a+leak+would+be+sound,+but+undesirable.)%0A++++++++let+label+=+self.label.clone();%0A%0A++++++++//+SAFETY:+The+caller+must+provide+a+%60dest%60+such+that+these+field+offsets+are+valid%0A++++++++//+to+write+to.%0A++++++++unsafe+%7B%0A++++++++++++//+Clone+the+unsized+field+directly+from+%60self%60+to+%60dest%60.%0A++++++++++++self.contents.clone_to_uninit(dest.add(offset_of_contents));%0A%0A++++++++++++//+Now+write+all+the+sized+fields.%0A++++++++++++//%0A++++++++++++//+Note+that+we+only+do+this+once+all+of+the+clone()+and+clone_to_uninit()+calls%0A++++++++++++//+have+completed,+and+therefore+we+know+that+there+are+no+more+possible+panics;%0A++++++++++++//+this+ensures+no+memory+leaks+in+case+of+panic.%0A++++++++++++dest.add(offset_of!(Self,+label)).cast::%3CString%3E().write(label);%0A++++++++%7D%0A++++++++//+All+fields+of+the+struct+have+been+initialized;+therefore,+the+struct+is+initialized,%0A++++++++//+and+we+have+satisfied+our+%60unsafe+impl+CloneToUninit%60+obligations.%0A++++%7D%0A%7D%0A%0Afn+main()+%7B%0A++++//+Construct+MyDst%3C%5Bu8;+4%5D%3E,+then+coerce+to+MyDst%3C%5Bu8%5D%3E.%0A++++let+first:+Rc%3CMyDst%3C%5Bu8%5D%3E%3E+=+Rc::new(MyDst+%7B%0A++++++++label:+String::from(%22hello%22),%0A++++++++contents:+%5B1,+2,+3,+4%5D,%0A++++%7D);%0A%0A++++let+mut+second+=+first.clone();%0A++++//+make_mut()+will+call+clone_to_uninit().%0A++++for+elem+in+Rc::make_mut(%26mut+second).contents.iter_mut()+%7B%0A++++++++*elem+*=+10;%0A++++%7D%0A%0A++++assert_eq!(first.contents,+%5B1,+2,+3,+4%5D);%0A++++assert_eq!(second.contents,+%5B10,+20,+30,+40%5D);%0A++++assert_eq!(second.label,+%22hello%22);%0A%7D&version=nightly&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#see-also) See Also ------------------------------------------------------------------------------------------ * [`Clone::clone_from`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from "method std::clone::Clone::clone_from") is a safe function which may be used instead when [`Self: Sized`](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") and the destination is already initialized; it may be able to reuse allocations owned by the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be uninitialized. * [`ToOwned`](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html) , which allocates a new destination container. Required Methods[§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#required-methods) ---------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#511) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. This is analogous to `std::ptr::write(dest.cast(), self.clone())`, except that `Self` may be a dynamically-sized type ([`!Sized`](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") ). Before this function is called, `dest` may point to uninitialized memory. After this function is called, `dest` will point to initialized memory; it will be sound to create a `&Self` reference from the pointer with the [pointer metadata](https://doc.rust-lang.org/stable/std/ptr/fn.metadata.html "fn std::ptr::metadata") from `self`. ##### [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#safety-1) Safety Behavior is undefined if any of the following conditions are violated: * `dest` must be [valid](https://doc.rust-lang.org/stable/std/ptr/index.html#safety "mod std::ptr") for writes for `size_of_val(self)` bytes. * `dest` must be properly aligned to `align_of_val(self)`. ##### [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#panics) Panics This function may panic. (For example, it might panic if memory allocation for a clone of a value owned by `self` fails.) If the call panics, then `*dest` should be treated as uninitialized memory; it must not be read or dropped, because even if it was previously valid, it may have been partially overwritten. The caller may wish to take care to deallocate the allocation pointed to by `dest`, if applicable, to avoid a memory leak (but this is not a requirement). Implementors should avoid leaking values by, upon unwinding, dropping all component values that might have already been created. (For example, if a `[Foo]` of length 3 is being cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo` cloned should be dropped.) Implementors[§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#implementors) -------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#535) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-str) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for [str](https://doc.rust-lang.org/stable/std/primitive.str.html) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#557) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-ByteStr) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#545) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-CStr) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for [CStr](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1343-1350) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-OsStr) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3517-3524) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-Path) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#524) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-%5BT%5D) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for [\[T\]](https://doc.rust-lang.org/stable/std/primitive.slice.html) where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , --- # Alignment in std::fmt - Rust [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#) --------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[fmt](https://doc.rust-lang.org/stable/std/fmt/index.html) Enum Alignment Copy item path ============================= 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#25) pub enum Alignment { Left, Right, Center, } Expand description Possible alignments returned by `Formatter::align` Variants[§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#variants) ----------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#variant.Left) 1.28.0 ### Left Indication that contents should be left-aligned. [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#variant.Right) 1.28.0 ### Right Indication that contents should be right-aligned. [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#variant.Center) 1.28.0 ### Center Indication that contents should be center-aligned. Trait Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#trait-implementations) ------------------------------------------------------------------------------------------------------------- 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Clone-for-Alignment) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Debug-for-Alignment) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-PartialEq-for-Alignment) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Copy-for-Alignment) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Eq-for-Alignment) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-StructuralPartialEq-for-Alignment) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#synthetic-implementations) ---------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Freeze-for-Alignment) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-RefUnwindSafe-for-Alignment) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Send-for-Alignment) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Sync-for-Alignment) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Unpin-for-Alignment) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-UnwindSafe-for-Alignment) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#blanket-implementations) ----------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Sign in std::fmt - Rust [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#) ----------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[fmt](https://doc.rust-lang.org/stable/std/fmt/index.html) Enum Sign Copy item path ======================== [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#261) pub enum Sign { Plus, Minus, } 🔬This is a nightly-only experimental API. (`formatting_options` [#118117](https://github.com/rust-lang/rust/issues/118117) ) Expand description The signedness of a [`Formatter`](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") (or of a [`FormattingOptions`](https://doc.rust-lang.org/stable/std/fmt/struct.FormattingOptions.html "struct std::fmt::FormattingOptions") ). Variants[§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#variants) ------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#variant.Plus) ### Plus 🔬This is a nightly-only experimental API. (`formatting_options` [#118117](https://github.com/rust-lang/rust/issues/118117) ) Represents the `+` flag. [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#variant.Minus) ### Minus 🔬This is a nightly-only experimental API. (`formatting_options` [#118117](https://github.com/rust-lang/rust/issues/118117) ) Represents the `-` flag. Trait Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#trait-implementations) -------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Clone-for-Sign) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Debug-for-Sign) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-PartialEq-for-Sign) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Copy-for-Sign) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Eq-for-Sign) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-StructuralPartialEq-for-Sign) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Freeze-for-Sign) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-RefUnwindSafe-for-Sign) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Send-for-Sign) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Sync-for-Sign) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Unpin-for-Sign) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-UnwindSafe-for-Sign) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # DebugAsHex in std::fmt - Rust [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[fmt](https://doc.rust-lang.org/stable/std/fmt/index.html) Enum DebugAsHex Copy item path ============================== [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#272) pub enum DebugAsHex { Lower, Upper, } 🔬This is a nightly-only experimental API. (`formatting_options` [#118117](https://github.com/rust-lang/rust/issues/118117) ) Expand description Specifies whether the [`Debug`](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") trait should use lower-/upper-case hexadecimal or normal integers. Variants[§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#variants) ------------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#variant.Lower) ### Lower 🔬This is a nightly-only experimental API. (`formatting_options` [#118117](https://github.com/rust-lang/rust/issues/118117) ) Use lower-case hexadecimal integers for the `Debug` trait (like [the `x?` type](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-traits) ). [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#variant.Upper) ### Upper 🔬This is a nightly-only experimental API. (`formatting_options` [#118117](https://github.com/rust-lang/rust/issues/118117) ) Use upper-case hexadecimal integers for the `Debug` trait (like [the `X?` type](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-traits) ). Trait Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#trait-implementations) -------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Clone-for-DebugAsHex) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Debug-for-DebugAsHex) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-PartialEq-for-DebugAsHex) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Copy-for-DebugAsHex) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Eq-for-DebugAsHex) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-StructuralPartialEq-for-DebugAsHex) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Freeze-for-DebugAsHex) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-RefUnwindSafe-for-DebugAsHex) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Send-for-DebugAsHex) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Sync-for-DebugAsHex) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Unpin-for-DebugAsHex) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-UnwindSafe-for-DebugAsHex) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # TypeId in std::any - Rust [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#) ----------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[any](https://doc.rust-lang.org/stable/std/any/index.html) Struct TypeId Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#712) pub struct TypeId { /* private fields */ } Expand description A `TypeId` represents a globally unique identifier for a type. Each `TypeId` is an opaque object which does not allow inspection of what’s inside but does allow basic operations such as cloning, comparison, printing, and showing. A `TypeId` is currently only available for types which ascribe to `'static`, but this limitation may be removed in the future. While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth noting that the hashes and ordering will vary between Rust releases. Beware of relying on them inside of your code! [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#danger-of-improper-variance) Danger of Improper Variance ------------------------------------------------------------------------------------------------------------------------ You might think that subtyping is impossible between two static types, but this is false; there exists a static type with a static subtype. To wit, `fn(&str)`, which is short for `for<'any> fn(&'any str)`, and `fn(&'static str)`, are two distinct, static types, and yet, `fn(&str)` is a subtype of `fn(&'static str)`, since any value of type `fn(&str)` can be used where a value of type `fn(&'static str)` is needed. This means that abstractions around `TypeId`, despite its `'static` bound on arguments, still need to worry about unnecessary and improper variance: it is advisable to strive for invariance first. The usability impact will be negligible, while the reduction in the risk of unsoundness will be most welcome. ### [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#examples) Examples Suppose `SubType` is a subtype of `SuperType`, that is, a value of type `SubType` can be used wherever a value of type `SuperType` is expected. Suppose also that `CoVar` is a generic type, which is covariant over `T` (like many other types, including `PhantomData` and `Vec`). Then, by covariance, `CoVar` is a subtype of `CoVar`, that is, a value of type `CoVar` can be used wherever a value of type `CoVar` is expected. Then if `CoVar` relies on `TypeId::of::()` to uphold any invariants, those invariants may be broken because a value of type `CoVar` can be created without going through any of its methods, like so: type SubType = fn(&()); type SuperType = fn(&'static ()); type CoVar = Vec; // imagine something more complicated let sub: CoVar = CoVar::new(); // we have a `CoVar` instance without // *ever* having called `CoVar::::new()`! let fake_super: CoVar = sub; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++type+SubType+=+fn(%26());%0A++++type+SuperType+=+fn(%26%27static+());%0A++++type+CoVar%3CT%3E+=+Vec%3CT%3E;+//+imagine+something+more+complicated%0A++++%0A++++let+sub:+CoVar%3CSubType%3E+=+CoVar::new();%0A++++//+we+have+a+%60CoVar%3CSuperType%3E%60+instance+without%0A++++//+*ever*+having+called+%60CoVar::%3CSuperType%3E::new()%60!%0A++++let+fake_super:+CoVar%3CSuperType%3E+=+sub;%0A%7D&edition=2024 "Run code") The following is an example program that tries to use `TypeId::of` to implement a generic type `Unique` that guarantees unique instances for each `Unique`, that is, and for each type `T` there can be at most one value of type `Unique` at any time. mod unique { use std::any::TypeId; use std::collections::BTreeSet; use std::marker::PhantomData; use std::sync::Mutex; static ID_SET: Mutex> = Mutex::new(BTreeSet::new()); // TypeId has only covariant uses, which makes Unique covariant over TypeAsId 🚨 #[derive(Debug, PartialEq)] pub struct Unique( // private field prevents creation without `new` outside this module PhantomData, ); impl Unique { pub fn new() -> Option { let mut set = ID_SET.lock().unwrap(); (set.insert(TypeId::of::())).then(|| Self(PhantomData)) } } impl Drop for Unique { fn drop(&mut self) { let mut set = ID_SET.lock().unwrap(); (!set.remove(&TypeId::of::())).then(|| panic!("duplicity detected")); } } } use unique::Unique; // `OtherRing` is a subtype of `TheOneRing`. Both are 'static, and thus have a TypeId. type TheOneRing = fn(&'static ()); type OtherRing = fn(&()); fn main() { let the_one_ring: Unique = Unique::new().unwrap(); assert_eq!(Unique::::new(), None); let other_ring: Unique = Unique::new().unwrap(); // Use that `Unique` is a subtype of `Unique` 🚨 let fake_one_ring: Unique = other_ring; assert_eq!(fake_one_ring, the_one_ring); std::mem::forget(fake_one_ring); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Amod+unique+%7B%0A++++use+std::any::TypeId;%0A++++use+std::collections::BTreeSet;%0A++++use+std::marker::PhantomData;%0A++++use+std::sync::Mutex;%0A%0A++++static+ID_SET:+Mutex%3CBTreeSet%3CTypeId%3E%3E+=+Mutex::new(BTreeSet::new());%0A%0A++++//+TypeId+has+only+covariant+uses,+which+makes+Unique+covariant+over+TypeAsId+%F0%9F%9A%A8%0A++++%23%5Bderive(Debug,+PartialEq)%5D%0A++++pub+struct+Unique%3CTypeAsId:+%27static%3E(%0A++++++++//+private+field+prevents+creation+without+%60new%60+outside+this+module%0A++++++++PhantomData%3CTypeAsId%3E,%0A++++);%0A%0A++++impl%3CTypeAsId:+%27static%3E+Unique%3CTypeAsId%3E+%7B%0A++++++++pub+fn+new()+-%3E+Option%3CSelf%3E+%7B%0A++++++++++++let+mut+set+=+ID_SET.lock().unwrap();%0A++++++++++++(set.insert(TypeId::of::%3CTypeAsId%3E())).then(%7C%7C+Self(PhantomData))%0A++++++++%7D%0A++++%7D%0A%0A++++impl%3CTypeAsId:+%27static%3E+Drop+for+Unique%3CTypeAsId%3E+%7B%0A++++++++fn+drop(%26mut+self)+%7B%0A++++++++++++let+mut+set+=+ID_SET.lock().unwrap();%0A++++++++++++(!set.remove(%26TypeId::of::%3CTypeAsId%3E())).then(%7C%7C+panic!(%22duplicity+detected%22));%0A++++++++%7D%0A++++%7D%0A%7D%0A%0Ause+unique::Unique;%0A%0A//+%60OtherRing%60+is+a+subtype+of+%60TheOneRing%60.+Both+are+%27static,+and+thus+have+a+TypeId.%0Atype+TheOneRing+=+fn(%26%27static+());%0Atype+OtherRing+=+fn(%26());%0A%0Afn+main()+%7B%0A++++let+the_one_ring:+Unique%3CTheOneRing%3E+=+Unique::new().unwrap();%0A++++assert_eq!(Unique::%3CTheOneRing%3E::new(),+None);%0A%0A++++let+other_ring:+Unique%3COtherRing%3E+=+Unique::new().unwrap();%0A++++//+Use+that+%60Unique%3COtherRing%3E%60+is+a+subtype+of+%60Unique%3CTheOneRing%3E%60+%F0%9F%9A%A8%0A++++let+fake_one_ring:+Unique%3CTheOneRing%3E+=+other_ring;%0A++++assert_eq!(fake_one_ring,+the_one_ring);%0A%0A++++std::mem::forget(fake_one_ring);%0A%7D&edition=2024 "Run code") Implementations[§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#implementations) ------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#760) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-TypeId) ### impl [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") 1.0.0 (const: 1.91.0) · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#778) #### pub const fn [of](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.of) () -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Returns the `TypeId` of the generic type parameter. ##### [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#examples-1) Examples use std::any::{Any, TypeId}; fn is_string(_s: &T) -> bool { TypeId::of::() == TypeId::of::() } assert_eq!(is_string(&0), false); assert_eq!(is_string(&"cookie monster".to_string()), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::any::%7BAny,+TypeId%7D;%0A++++%0A++++fn+is_string%3CT:+?Sized+%2B+Any%3E(_s:+%26T)+-%3E+bool+%7B%0A++++++++TypeId::of::%3CString%3E()+==+TypeId::of::%3CT%3E()%0A++++%7D%0A++++%0A++++assert_eq!(is_string(%260),+false);%0A++++assert_eq!(is_string(%26%22cookie+monster%22.to_string()),+true);%0A%7D&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#trait-implementations) ------------------------------------------------------------------------------------------------------------ 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#709) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Clone-for-TypeId) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#709) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#821) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Debug-for-TypeId) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#822) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#796) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Hash-for-TypeId) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#798) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) (&self, state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Ord-for-TypeId) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.cmp) #### fn [cmp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) (&self, other: &[TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") This method returns an [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") between `self` and `other`. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1021-1023) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.max) #### fn [max](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the maximum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1060-1062) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.min) #### fn [min](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the minimum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1086-1088) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.clamp) #### fn [clamp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (self, min: Self, max: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Restrict a value to a certain interval. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#730) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-PartialEq-for-TypeId) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#732) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-PartialOrd-for-TypeId) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.partial_cmp) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.lt) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.le) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.gt) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.ge) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Copy-for-TypeId) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#709) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Eq-for-TypeId) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#723) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Send-for-TypeId) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#726) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Sync-for-TypeId) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#synthetic-implementations) --------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Freeze-for-TypeId) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-RefUnwindSafe-for-TypeId) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Unpin-for-TypeId) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-UnwindSafe-for-TypeId) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#blanket-implementations) ---------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # TryReserveErrorKind in std::collections - Rust [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#) ------------------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[collections](https://doc.rust-lang.org/stable/std/collections/index.html) Enum TryReserveErrorKind Copy item path ======================================= [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#100) pub enum TryReserveErrorKind { CapacityOverflow, AllocError { layout: Layout, /* private fields */ }, } 🔬This is a nightly-only experimental API. (`try_reserve_kind` [#48043](https://github.com/rust-lang/rust/issues/48043) ) Expand description Details of the allocation that caused a `TryReserveError` Variants[§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#variants) ----------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#variant.CapacityOverflow) ### CapacityOverflow 🔬This is a nightly-only experimental API. (`try_reserve_kind` [#48043](https://github.com/rust-lang/rust/issues/48043) ) Error due to the computed capacity exceeding the collection’s maximum (usually `isize::MAX` bytes). [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#variant.AllocError) ### AllocError 🔬This is a nightly-only experimental API. (`try_reserve_kind` [#48043](https://github.com/rust-lang/rust/issues/48043) ) The memory allocator returned an error #### Fields [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#variant.AllocError.field.layout) `layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") ` 🔬This is a nightly-only experimental API. (`try_reserve_kind` [#48043](https://github.com/rust-lang/rust/issues/48043) ) The layout of allocation request that failed Trait Implementations[§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#trait-implementations) ------------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Clone-for-TryReserveErrorKind) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Debug-for-TryReserveErrorKind) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#143) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-From%3CLayoutError%3E-for-TryReserveErrorKind) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[LayoutError](https://doc.rust-lang.org/stable/std/alloc/struct.LayoutError.html "struct std::alloc::LayoutError") \> for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#146) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (\_: [LayoutError](https://doc.rust-lang.org/stable/std/alloc/struct.LayoutError.html "struct std::alloc::LayoutError") ) -> [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") Always evaluates to [`TryReserveErrorKind::CapacityOverflow`](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#variant.CapacityOverflow "variant std::collections::TryReserveErrorKind::CapacityOverflow") . [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#133) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-From%3CTryReserveErrorKind%3E-for-TryReserveError) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") \> for [TryReserveError](https://doc.rust-lang.org/stable/std/collections/struct.TryReserveError.html "struct std::collections::TryReserveError") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#135) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (kind: [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") ) -> [TryReserveError](https://doc.rust-lang.org/stable/std/collections/struct.TryReserveError.html "struct std::collections::TryReserveError") Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-PartialEq-for-TryReserveErrorKind) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Eq-for-TryReserveErrorKind) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-StructuralPartialEq-for-TryReserveErrorKind) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#synthetic-implementations) ---------------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Freeze-for-TryReserveErrorKind) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-RefUnwindSafe-for-TryReserveErrorKind) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Send-for-TryReserveErrorKind) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Sync-for-TryReserveErrorKind) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Unpin-for-TryReserveErrorKind) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-UnwindSafe-for-TryReserveErrorKind) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#blanket-implementations) ----------------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.from-2) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # BacktraceStyle in std::panic - Rust [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#) --------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[panic](https://doc.rust-lang.org/stable/std/panic/index.html) Enum BacktraceStyle Copy item path ================================== [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#435-443) #[non_exhaustive]pub enum BacktraceStyle { Short, Full, Off, } 🔬This is a nightly-only experimental API. (`panic_backtrace_config` [#93346](https://github.com/rust-lang/rust/issues/93346) ) Expand description The configuration for whether and how the default panic hook will capture and display the backtrace. Variants (Non-exhaustive)[§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#variants) ----------------------------------------------------------------------------------------------------------- This enum is marked as non-exhaustive Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants. [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#variant.Short) ### Short 🔬This is a nightly-only experimental API. (`panic_backtrace_config` [#93346](https://github.com/rust-lang/rust/issues/93346) ) Prints a terser backtrace which ideally only contains relevant information. [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#variant.Full) ### Full 🔬This is a nightly-only experimental API. (`panic_backtrace_config` [#93346](https://github.com/rust-lang/rust/issues/93346) ) Prints a backtrace with all possible information. [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#variant.Off) ### Off 🔬This is a nightly-only experimental API. (`panic_backtrace_config` [#93346](https://github.com/rust-lang/rust/issues/93346) ) Disable collecting and displaying backtraces. Trait Implementations[§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#trait-implementations) -------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Clone-for-BacktraceStyle) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Debug-for-BacktraceStyle) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-PartialEq-for-BacktraceStyle) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Copy-for-BacktraceStyle) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Eq-for-BacktraceStyle) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-StructuralPartialEq-for-BacktraceStyle) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Freeze-for-BacktraceStyle) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-RefUnwindSafe-for-BacktraceStyle) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Send-for-BacktraceStyle) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Sync-for-BacktraceStyle) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Unpin-for-BacktraceStyle) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-UnwindSafe-for-BacktraceStyle) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # IntErrorKind in std::num - Rust [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#) --------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[num](https://doc.rust-lang.org/stable/std/num/index.html) Enum IntErrorKind Copy item path ================================ 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#83) #[non_exhaustive]pub enum IntErrorKind { Empty, InvalidDigit, PosOverflow, NegOverflow, Zero, } Expand description Enum to store the various types of errors that can cause parsing an integer to fail. [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#example) Example ------------------------------------------------------------------------------------ if let Err(e) = i32::from_str_radix("a12", 10) { println!("Failed conversion to i32: {:?}", e.kind()); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0Aif+let+Err(e)+=+i32::from_str_radix(%22a12%22,+10)+%7B%0A++++println!(%22Failed+conversion+to+i32:+%7B:?%7D%22,+e.kind());%0A%7D%0A%7D&edition=2024 "Run code") Variants (Non-exhaustive)[§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#variants) ------------------------------------------------------------------------------------------------------- This enum is marked as non-exhaustive Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants. [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#variant.Empty) 1.55.0 ### Empty Value being parsed is empty. This variant will be constructed when parsing an empty string. [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#variant.InvalidDigit) 1.55.0 ### InvalidDigit Contains an invalid digit in its context. Among other causes, this variant will be constructed when parsing a string that contains a non-ASCII char. This variant is also constructed when a `+` or `-` is misplaced within a string either on its own or in the middle of a number. [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#variant.PosOverflow) 1.55.0 ### PosOverflow Integer is too large to store in target integer type. [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#variant.NegOverflow) 1.55.0 ### NegOverflow Integer is too small to store in target integer type. [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#variant.Zero) 1.55.0 ### Zero Value was Zero This variant will be emitted when the parsing string has a value of zero, which would be illegal for non-zero types. Trait Implementations[§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#trait-implementations) ---------------------------------------------------------------------------------------------------------------- 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Clone-for-IntErrorKind) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Debug-for-IntErrorKind) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Hash-for-IntErrorKind) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where \_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-PartialEq-for-IntErrorKind) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Copy-for-IntErrorKind) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Eq-for-IntErrorKind) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-StructuralPartialEq-for-IntErrorKind) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Freeze-for-IntErrorKind) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-RefUnwindSafe-for-IntErrorKind) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Send-for-IntErrorKind) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Sync-for-IntErrorKind) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Unpin-for-IntErrorKind) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-UnwindSafe-for-IntErrorKind) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#blanket-implementations) -------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # SeekFrom in std::io - Rust [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#) ------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) ::[io](https://doc.rust-lang.org/stable/std/io/index.html) Enum SeekFrom Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2185-2205) pub enum SeekFrom { Start(u64), End(i64), Current(i64), } Expand description Enumeration of possible methods to seek within an I/O object. It is used by the [`Seek`](https://doc.rust-lang.org/stable/std/io/trait.Seek.html "trait std::io::Seek") trait. Variants[§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#variants) --------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#variant.Start) 1.0.0 ### Start([u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) Sets the offset to the provided number of bytes. [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#variant.End) 1.0.0 ### End([i64](https://doc.rust-lang.org/stable/std/primitive.i64.html) ) Sets the offset to the size of this object plus the specified number of bytes. It is possible to seek beyond the end of an object, but it’s an error to seek before byte 0. [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#variant.Current) 1.0.0 ### Current([i64](https://doc.rust-lang.org/stable/std/primitive.i64.html) ) Sets the offset to the current position plus the specified number of bytes. It is possible to seek beyond the end of an object, but it’s an error to seek before byte 0. Trait Implementations[§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#trait-implementations) ----------------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Clone-for-SeekFrom) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Debug-for-SeekFrom) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-PartialEq-for-SeekFrom) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Copy-for-SeekFrom) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Eq-for-SeekFrom) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-StructuralPartialEq-for-SeekFrom) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#synthetic-implementations) -------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Freeze-for-SeekFrom) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-RefUnwindSafe-for-SeekFrom) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Send-for-SeekFrom) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Sync-for-SeekFrom) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Unpin-for-SeekFrom) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-UnwindSafe-for-SeekFrom) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#blanket-implementations) --------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Shutdown in std::net - Rust [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[net](https://doc.rust-lang.org/stable/std/net/index.html) Enum Shutdown Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#52-72) pub enum Shutdown { Read, Write, Both, } Expand description Possible values which can be passed to the [`TcpStream::shutdown`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.shutdown "method std::net::TcpStream::shutdown") method. Variants[§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#variants) ---------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#variant.Read) 1.0.0 ### Read The reading portion of the [`TcpStream`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") should be shut down. All currently blocked and future [reads](https://doc.rust-lang.org/stable/std/io/trait.Read.html "io::Read") will return `[Ok](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") (0)`. [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#variant.Write) 1.0.0 ### Write The writing portion of the [`TcpStream`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") should be shut down. All currently blocked and future [writes](https://doc.rust-lang.org/stable/std/io/trait.Write.html "io::Write") will return an error. [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#variant.Both) 1.0.0 ### Both Both the reading and the writing portions of the [`TcpStream`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html "struct std::net::TcpStream") should be shut down. See [`Shutdown::Read`](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#variant.Read "variant std::net::Shutdown::Read") and [`Shutdown::Write`](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#variant.Write "variant std::net::Shutdown::Write") for more information. Trait Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#trait-implementations) ------------------------------------------------------------------------------------------------------------ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Clone-for-Shutdown) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Debug-for-Shutdown) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-PartialEq-for-Shutdown) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Copy-for-Shutdown) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Eq-for-Shutdown) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-StructuralPartialEq-for-Shutdown) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#synthetic-implementations) --------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Freeze-for-Shutdown) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-RefUnwindSafe-for-Shutdown) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Send-for-Shutdown) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Sync-for-Shutdown) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Unpin-for-Shutdown) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-UnwindSafe-for-Shutdown) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#blanket-implementations) ---------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # VarError in std::env - Rust [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#) ------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[env](https://doc.rust-lang.org/stable/std/env/index.html) Enum VarError Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#273-284) pub enum VarError { NotPresent, NotUnicode(OsString), } Expand description The error type for operations interacting with environment variables. Possibly returned from [`env::var()`](https://doc.rust-lang.org/stable/std/env/fn.var.html "fn std::env::var") . Variants[§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#variants) ---------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#variant.NotPresent) 1.0.0 ### NotPresent The specified environment variable was not present in the current process’s environment. [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#variant.NotUnicode) 1.0.0 ### NotUnicode([OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") ) The specified environment variable was found, but it did not contain valid unicode data. The found data is returned as a payload of this variant. Trait Implementations[§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#trait-implementations) ------------------------------------------------------------------------------------------------------------ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Clone-for-VarError) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Debug-for-VarError) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#287-296) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Display-for-VarError) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#288-295) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#299) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Error-for-VarError) ### impl [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#111) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.source) #### fn [source](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&(dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") + 'static)> Returns the lower-level source of this error, if any. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#137) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.description) #### fn [description](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#147) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.cause) #### fn [cause](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.cause) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") \> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#210) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.provide) #### fn [provide](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) <'a>(&'a self, request: &mut [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") <'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301) ) Provides type-based access to context intended for error reports. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-PartialEq-for-VarError) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Eq-for-VarError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-StructuralPartialEq-for-VarError) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#synthetic-implementations) --------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Freeze-for-VarError) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-RefUnwindSafe-for-VarError) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Send-for-VarError) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Sync-for-VarError) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Unpin-for-VarError) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-UnwindSafe-for-VarError) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#blanket-implementations) ---------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/env/enum.VarError.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # FpCategory in std::num - Rust [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#) ----------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[num](https://doc.rust-lang.org/stable/std/num/index.html) Enum FpCategory Copy item path ============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1339) pub enum FpCategory { Nan, Infinite, Zero, Subnormal, Normal, } Expand description A classification of floating point numbers. This `enum` is used as the return type for [`f32::classify`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.classify "method f32::classify") and [`f64::classify`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.classify "method f64::classify") . See their documentation for more. [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#examples) Examples ------------------------------------------------------------------------------------ use std::num::FpCategory; let num = 12.4_f32; let inf = f32::INFINITY; let zero = 0f32; let sub: f32 = 1.1754942e-38; let nan = f32::NAN; assert_eq!(num.classify(), FpCategory::Normal); assert_eq!(inf.classify(), FpCategory::Infinite); assert_eq!(zero.classify(), FpCategory::Zero); assert_eq!(sub.classify(), FpCategory::Subnormal); assert_eq!(nan.classify(), FpCategory::Nan); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::num::FpCategory;%0A++++%0A++++let+num+=+12.4_f32;%0A++++let+inf+=+f32::INFINITY;%0A++++let+zero+=+0f32;%0A++++let+sub:+f32+=+1.1754942e-38;%0A++++let+nan+=+f32::NAN;%0A++++%0A++++assert_eq!(num.classify(),+FpCategory::Normal);%0A++++assert_eq!(inf.classify(),+FpCategory::Infinite);%0A++++assert_eq!(zero.classify(),+FpCategory::Zero);%0A++++assert_eq!(sub.classify(),+FpCategory::Subnormal);%0A++++assert_eq!(nan.classify(),+FpCategory::Nan);%0A%7D&edition=2024 "Run code") Variants[§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variants) ------------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Nan) 1.0.0 ### Nan NaN (not a number): this value results from calculations like `(-1.0).sqrt()`. See [the documentation for `f32`](https://doc.rust-lang.org/stable/std/primitive.f32.html "primitive f32") for more information on the unusual properties of NaN. [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Infinite) 1.0.0 ### Infinite Positive or negative infinity, which often results from dividing a nonzero number by zero. [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Zero) 1.0.0 ### Zero Positive or negative zero. See [the documentation for `f32`](https://doc.rust-lang.org/stable/std/primitive.f32.html "primitive f32") for more information on the signedness of zeroes. [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Subnormal) 1.0.0 ### Subnormal “Subnormal” or “denormal” floating point representation (less precise, relative to their magnitude, than [`Normal`](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Normal "variant std::num::FpCategory::Normal") ). Subnormal numbers are larger in magnitude than [`Zero`](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Zero "variant std::num::FpCategory::Zero") but smaller in magnitude than all [`Normal`](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Normal "variant std::num::FpCategory::Normal") numbers. [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#variant.Normal) 1.0.0 ### Normal A regular floating point number, not any of the exceptional categories. The smallest positive normal numbers are [`f32::MIN_POSITIVE`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MIN_POSITIVE "associated constant f32::MIN_POSITIVE") and [`f64::MIN_POSITIVE`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MIN_POSITIVE "associated constant f64::MIN_POSITIVE") , and the largest positive normal numbers are [`f32::MAX`](https://doc.rust-lang.org/stable/std/primitive.f32.html#associatedconstant.MAX "associated constant f32::MAX") and [`f64::MAX`](https://doc.rust-lang.org/stable/std/primitive.f64.html#associatedconstant.MAX "associated constant f64::MAX") . (Unlike signed integers, floating point numbers are symmetric in their range, so negating any of these constants will produce their negative counterpart.) Trait Implementations[§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#trait-implementations) -------------------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Clone-for-FpCategory) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Debug-for-FpCategory) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-PartialEq-for-FpCategory) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Copy-for-FpCategory) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Eq-for-FpCategory) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-StructuralPartialEq-for-FpCategory) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Freeze-for-FpCategory) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-RefUnwindSafe-for-FpCategory) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Send-for-FpCategory) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Sync-for-FpCategory) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Unpin-for-FpCategory) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-UnwindSafe-for-FpCategory) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # ErrorKind in std::io - Rust [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#) -------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[io](https://doc.rust-lang.org/stable/std/io/index.html) Enum ErrorKind Copy item path ============================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#228-449) #[non_exhaustive]pub enum ErrorKind { Show 41 variants NotFound, PermissionDenied, ConnectionRefused, ConnectionReset, HostUnreachable, NetworkUnreachable, ConnectionAborted, NotConnected, AddrInUse, AddrNotAvailable, NetworkDown, BrokenPipe, AlreadyExists, WouldBlock, NotADirectory, IsADirectory, DirectoryNotEmpty, ReadOnlyFilesystem, FilesystemLoop, StaleNetworkFileHandle, InvalidInput, InvalidData, TimedOut, WriteZero, StorageFull, NotSeekable, QuotaExceeded, FileTooLarge, ResourceBusy, ExecutableFileBusy, Deadlock, CrossesDevices, TooManyLinks, InvalidFilename, ArgumentListTooLong, Interrupted, Unsupported, UnexpectedEof, OutOfMemory, InProgress, Other, } Expand description A list specifying general categories of I/O error. This list is intended to grow over time and it is not recommended to exhaustively match against it. It is used with the [`io::Error`](https://doc.rust-lang.org/stable/std/io/struct.Error.html "struct std::io::Error") type. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#handling-errors-and-matching-on-errorkind) Handling errors and matching on `ErrorKind` ------------------------------------------------------------------------------------------------------------------------------------------------------ In application code, use `match` for the `ErrorKind` values you are expecting; use `_` to match “all other errors”. In comprehensive and thorough tests that want to verify that a test doesn’t return any known incorrect error kind, you may want to cut-and-paste the current full list of errors from here into your test code, and then match `_` as the correct case. This seems counterintuitive, but it will make your tests more robust. In particular, if you want to verify that your code does produce an unrecognized error kind, the robust solution is to check for all the recognized error kinds and fail in those cases. Variants (Non-exhaustive)[§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variants) --------------------------------------------------------------------------------------------------- This enum is marked as non-exhaustive Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotFound) 1.0.0 ### NotFound An entity was not found, often a file. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.PermissionDenied) 1.0.0 ### PermissionDenied The operation lacked the necessary privileges to complete. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ConnectionRefused) 1.0.0 ### ConnectionRefused The connection was refused by the remote server. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ConnectionReset) 1.0.0 ### ConnectionReset The connection was reset by the remote server. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.HostUnreachable) 1.83.0 ### HostUnreachable The remote host is not reachable. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NetworkUnreachable) 1.83.0 ### NetworkUnreachable The network containing the remote host is not reachable. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ConnectionAborted) 1.0.0 ### ConnectionAborted The connection was aborted (terminated) by the remote server. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotConnected) 1.0.0 ### NotConnected The network operation failed because it was not connected yet. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.AddrInUse) 1.0.0 ### AddrInUse A socket address could not be bound because the address is already in use elsewhere. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.AddrNotAvailable) 1.0.0 ### AddrNotAvailable A nonexistent interface was requested or the requested address was not local. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NetworkDown) 1.83.0 ### NetworkDown The system’s networking is down. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.BrokenPipe) 1.0.0 ### BrokenPipe The operation failed because a pipe was closed. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.AlreadyExists) 1.0.0 ### AlreadyExists An entity already exists, often a file. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.WouldBlock) 1.0.0 ### WouldBlock The operation needs to block to complete, but the blocking operation was requested to not occur. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotADirectory) 1.83.0 ### NotADirectory A filesystem object is, unexpectedly, not a directory. For example, a filesystem path was specified where one of the intermediate directory components was, in fact, a plain file. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.IsADirectory) 1.83.0 ### IsADirectory The filesystem object is, unexpectedly, a directory. A directory was specified when a non-directory was expected. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.DirectoryNotEmpty) 1.83.0 ### DirectoryNotEmpty A non-empty directory was specified where an empty directory was expected. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ReadOnlyFilesystem) 1.83.0 ### ReadOnlyFilesystem The filesystem or storage medium is read-only, but a write operation was attempted. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.FilesystemLoop) ### FilesystemLoop 🔬This is a nightly-only experimental API. (`io_error_more` [#86442](https://github.com/rust-lang/rust/issues/86442) ) Loop in the filesystem or IO subsystem; often, too many levels of symbolic links. There was a loop (or excessively long chain) resolving a filesystem object or file IO object. On Unix this is usually the result of a symbolic link loop; or, of exceeding the system-specific limit on the depth of symlink traversal. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.StaleNetworkFileHandle) 1.83.0 ### StaleNetworkFileHandle Stale network file handle. With some network filesystems, notably NFS, an open file (or directory) can be invalidated by problems with the network or server. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.InvalidInput) 1.0.0 ### InvalidInput A parameter was incorrect. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.InvalidData) 1.2.0 ### InvalidData Data not valid for the operation were encountered. Unlike [`InvalidInput`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.InvalidInput "variant std::io::ErrorKind::InvalidInput") , this typically means that the operation parameters were valid, however the error was caused by malformed input data. For example, a function that reads a file into a string will error with `InvalidData` if the file’s contents are not valid UTF-8. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.TimedOut) 1.0.0 ### TimedOut The I/O operation’s timeout expired, causing it to be canceled. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.WriteZero) 1.0.0 ### WriteZero An error returned when an operation could not be completed because a call to [`write`](https://doc.rust-lang.org/stable/std/io/trait.Write.html#tymethod.write "method std::io::Write::write") returned [`Ok(0)`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Ok "variant std::result::Result::Ok") . This typically means that an operation could only succeed if it wrote a particular number of bytes but only a smaller number of bytes could be written. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.StorageFull) 1.83.0 ### StorageFull The underlying storage (typically, a filesystem) is full. This does not include out of quota errors. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.NotSeekable) 1.83.0 ### NotSeekable Seek on unseekable file. Seeking was attempted on an open file handle which is not suitable for seeking - for example, on Unix, a named pipe opened with `File::open`. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.QuotaExceeded) 1.85.0 ### QuotaExceeded Filesystem quota or some other kind of quota was exceeded. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.FileTooLarge) 1.83.0 ### FileTooLarge File larger than allowed or supported. This might arise from a hard limit of the underlying filesystem or file access API, or from an administratively imposed resource limitation. Simple disk full, and out of quota, have their own errors. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ResourceBusy) 1.83.0 ### ResourceBusy Resource is busy. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ExecutableFileBusy) 1.83.0 ### ExecutableFileBusy Executable file is busy. An attempt was made to write to a file which is also in use as a running program. (Not all operating systems detect this situation.) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.Deadlock) 1.83.0 ### Deadlock Deadlock (avoided). A file locking operation would result in deadlock. This situation is typically detected, if at all, on a best-effort basis. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.CrossesDevices) 1.85.0 ### CrossesDevices Cross-device or cross-filesystem (hard) link or rename. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.TooManyLinks) 1.83.0 ### TooManyLinks Too many (hard) links to the same filesystem object. The filesystem does not support making so many hardlinks to the same file. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.InvalidFilename) 1.87.0 ### InvalidFilename A filename was invalid. This error can also occur if a length limit for a name was exceeded. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.ArgumentListTooLong) 1.83.0 ### ArgumentListTooLong Program argument list too long. When trying to run an external program, a system or process limit on the size of the arguments would have been exceeded. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.Interrupted) 1.0.0 ### Interrupted This operation was interrupted. Interrupted operations can typically be retried. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.Unsupported) 1.53.0 ### Unsupported This operation is unsupported on this platform. This means that the operation can never succeed. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.UnexpectedEof) 1.6.0 ### UnexpectedEof An error returned when an operation could not be completed because an “end of file” was reached prematurely. This typically means that an operation could only succeed if it read a particular number of bytes but only a smaller number of bytes could be read. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.OutOfMemory) 1.54.0 ### OutOfMemory An operation could not be completed, because it failed to allocate enough memory. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.InProgress) ### InProgress 🔬This is a nightly-only experimental API. (`io_error_inprogress` [#130840](https://github.com/rust-lang/rust/issues/130840) ) The operation was partially successful and needs to be checked later on due to not blocking. [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#variant.Other) 1.0.0 ### Other A custom error that does not fall under any other I/O error kind. This can be used to construct your own [`Error`](https://doc.rust-lang.org/stable/std/io/struct.Error.html "struct std::io::Error") s that do not match any [`ErrorKind`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") . This [`ErrorKind`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") is not used by the standard library. Errors from the standard library that do not fall under any of the I/O error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern. New [`ErrorKind`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") s might be added in the future for some of those. Trait Implementations[§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#trait-implementations) ------------------------------------------------------------------------------------------------------------ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Clone-for-ErrorKind) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Debug-for-ErrorKind) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.60.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#504-517) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Display-for-ErrorKind) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#514-516) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, fmt: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Shows a human-readable description of the `ErrorKind`. This is similar to `impl Display for Error`, but doesn’t require first converting to Error. ##### [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#examples) Examples use std::io::ErrorKind; assert_eq!("entity not found", ErrorKind::NotFound.to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io::ErrorKind;%0A++++assert_eq!(%22entity+not+found%22,+ErrorKind::NotFound.to_string());%0A%7D&edition=2024 "Run code") 1.14.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#522-540) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-From%3CErrorKind%3E-for-Error) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") \> for [Error](https://doc.rust-lang.org/stable/std/io/struct.Error.html "struct std::io::Error") Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly. [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#537-539) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (kind: [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") ) -> [Error](https://doc.rust-lang.org/stable/std/io/struct.Error.html "struct std::io::Error") Converts an [`ErrorKind`](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") into an [`Error`](https://doc.rust-lang.org/stable/std/io/struct.Error.html "struct std::io::Error") . This conversion creates a new error with a simple representation of error kind. ##### [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#examples-1) Examples use std::io::{Error, ErrorKind}; let not_found = ErrorKind::NotFound; let error = Error::from(not_found); assert_eq!("entity not found", format!("{error}")); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::io::%7BError,+ErrorKind%7D;%0A++++%0A++++let+not_found+=+ErrorKind::NotFound;%0A++++let+error+=+Error::from(not_found);%0A++++assert_eq!(%22entity+not+found%22,+format!(%22%7Berror%7D%22));%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Hash-for-ErrorKind) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") \>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Ord-for-ErrorKind) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.cmp) #### fn [cmp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) (&self, other: &[ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") This method returns an [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") between `self` and `other`. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1021-1023) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.max) #### fn [max](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the maximum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1060-1062) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.min) #### fn [min](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the minimum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1086-1088) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.clamp) #### fn [clamp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (self, min: Self, max: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Restrict a value to a certain interval. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-PartialEq-for-ErrorKind) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-PartialOrd-for-ErrorKind) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.partial_cmp) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.lt) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.le) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.gt) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.ge) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Copy-for-ErrorKind) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Eq-for-ErrorKind) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-StructuralPartialEq-for-ErrorKind) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#synthetic-implementations) --------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Freeze-for-ErrorKind) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-RefUnwindSafe-for-ErrorKind) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Send-for-ErrorKind) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Sync-for-ErrorKind) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Unpin-for-ErrorKind) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-UnwindSafe-for-ErrorKind) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#blanket-implementations) ---------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # GetDisjointMutError in std::slice - Rust [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#) ------------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[slice](https://doc.rust-lang.org/stable/std/slice/index.html) Enum GetDisjointMutError Copy item path ======================================= 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5216) pub enum GetDisjointMutError { IndexOutOfBounds, OverlappingIndices, } Expand description The error type returned by [`get_disjoint_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_disjoint_mut "method slice::get_disjoint_mut") . It indicates one of two possible errors: * An index is out-of-bounds. * The same index appeared multiple times in the array (or different but overlapping indices when ranges are provided). [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#examples) Examples ----------------------------------------------------------------------------------------------- use std::slice::GetDisjointMutError; let v = &mut [1, 2, 3]; assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds)); assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::slice::GetDisjointMutError;%0A++++%0A++++let+v+=+%26mut+%5B1,+2,+3%5D;%0A++++assert_eq!(v.get_disjoint_mut(%5B0,+999%5D),+Err(GetDisjointMutError::IndexOutOfBounds));%0A++++assert_eq!(v.get_disjoint_mut(%5B1,+1%5D),+Err(GetDisjointMutError::OverlappingIndices));%0A%7D&edition=2024 "Run code") Variants[§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#variants) ----------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#variant.IndexOutOfBounds) 1.86.0 ### IndexOutOfBounds An index provided was out-of-bounds for the slice. [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#variant.OverlappingIndices) 1.86.0 ### OverlappingIndices Two indices provided were overlapping. Trait Implementations[§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#trait-implementations) ------------------------------------------------------------------------------------------------------------------------- 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Clone-for-GetDisjointMutError) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Debug-for-GetDisjointMutError) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5224) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Display-for-GetDisjointMutError) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5225) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#1084) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Error-for-GetDisjointMutError) ### impl [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#111) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.source) #### fn [source](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&(dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") + 'static)> Returns the lower-level source of this error, if any. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#137) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.description) #### fn [description](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#147) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.cause) #### fn [cause](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.cause) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") \> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#210) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.provide) #### fn [provide](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) <'a>(&'a self, request: &mut [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") <'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301) ) Provides type-based access to context intended for error reports. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-PartialEq-for-GetDisjointMutError) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Eq-for-GetDisjointMutError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-StructuralPartialEq-for-GetDisjointMutError) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#synthetic-implementations) ---------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Freeze-for-GetDisjointMutError) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-RefUnwindSafe-for-GetDisjointMutError) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Send-for-GetDisjointMutError) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Sync-for-GetDisjointMutError) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Unpin-for-GetDisjointMutError) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-UnwindSafe-for-GetDisjointMutError) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#blanket-implementations) ----------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Ordering in std::sync::atomic - Rust [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#) --------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) ::[atomic](https://doc.rust-lang.org/stable/std/sync/atomic/index.html) Enum Ordering Copy item path ============================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#439) #[non_exhaustive]pub enum Ordering { Relaxed, Release, Acquire, AcqRel, SeqCst, } Expand description Atomic memory orderings Memory orderings specify the way atomic operations synchronize memory. In its weakest [`Ordering::Relaxed`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Relaxed "variant std::sync::atomic::Ordering::Relaxed") , only the memory directly touched by the operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.SeqCst "variant std::sync::atomic::Ordering::SeqCst") operations synchronize other memory while additionally preserving a total order of such operations across all threads. Rust’s memory orderings are [the same as those of C++20](https://en.cppreference.com/w/cpp/atomic/memory_order) . For more information see the [nomicon](https://doc.rust-lang.org/stable/nomicon/atomics.html) . Variants (Non-exhaustive)[§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variants) ----------------------------------------------------------------------------------------------------------- This enum is marked as non-exhaustive Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants. [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Relaxed) 1.0.0 ### Relaxed No ordering constraints, only atomic operations. Corresponds to [`memory_order_relaxed`](https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering) in C++20. [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Release) 1.0.0 ### Release When coupled with a store, all previous operations become ordered before any load of this value with [`Acquire`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire "variant std::sync::atomic::Ordering::Acquire") (or stronger) ordering. In particular, all previous writes become visible to all threads that perform an [`Acquire`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire "variant std::sync::atomic::Ordering::Acquire") (or stronger) load of this value. Notice that using this ordering for an operation that combines loads and stores leads to a [`Relaxed`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Relaxed "variant std::sync::atomic::Ordering::Relaxed") load operation! This ordering is only applicable for operations that can perform a store. Corresponds to [`memory_order_release`](https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering) in C++20. [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire) 1.0.0 ### Acquire When coupled with a load, if the loaded value was written by a store operation with [`Release`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Release "variant std::sync::atomic::Ordering::Release") (or stronger) ordering, then all subsequent operations become ordered after that store. In particular, all subsequent loads will see data written before the store. Notice that using this ordering for an operation that combines loads and stores leads to a [`Relaxed`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Relaxed "variant std::sync::atomic::Ordering::Relaxed") store operation! This ordering is only applicable for operations that can perform a load. Corresponds to [`memory_order_acquire`](https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering) in C++20. [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.AcqRel) 1.0.0 ### AcqRel Has the effects of both [`Acquire`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire "variant std::sync::atomic::Ordering::Acquire") and [`Release`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Release "variant std::sync::atomic::Ordering::Release") together: For loads it uses [`Acquire`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire "variant std::sync::atomic::Ordering::Acquire") ordering. For stores it uses the [`Release`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Release "variant std::sync::atomic::Ordering::Release") ordering. Notice that in the case of `compare_and_swap`, it is possible that the operation ends up not performing any store and hence it has just [`Acquire`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire "variant std::sync::atomic::Ordering::Acquire") ordering. However, `AcqRel` will never perform [`Relaxed`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Relaxed "variant std::sync::atomic::Ordering::Relaxed") accesses. This ordering is only applicable for operations that combine both loads and stores. Corresponds to [`memory_order_acq_rel`](https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering) in C++20. [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.SeqCst) 1.0.0 ### SeqCst Like [`Acquire`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Acquire "variant std::sync::atomic::Ordering::Acquire") /[`Release`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.Release "variant std::sync::atomic::Ordering::Release") /[`AcqRel`](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#variant.AcqRel "variant std::sync::atomic::Ordering::AcqRel") (for load, store, and load-with-store operations, respectively) with the additional guarantee that all threads see all sequentially consistent operations in the same order. Corresponds to [`memory_order_seq_cst`](https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering) in C++20. Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#trait-implementations) -------------------------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Clone-for-Ordering) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Debug-for-Ordering) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Hash-for-Ordering) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where \_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-PartialEq-for-Ordering) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Copy-for-Ordering) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Eq-for-Ordering) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-StructuralPartialEq-for-Ordering) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Freeze-for-Ordering) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-RefUnwindSafe-for-Ordering) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Send-for-Ordering) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Sync-for-Ordering) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Unpin-for-Ordering) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-UnwindSafe-for-Ordering) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # FromBytesWithNulError in std::ffi - Rust [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#) --------------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[ffi](https://doc.rust-lang.org/stable/std/ffi/index.html) Enum FromBytesWithNulError Copy item path ========================================= 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#127) pub enum FromBytesWithNulError { InteriorNul { position: usize, }, NotNulTerminated, } Expand description An error indicating that a nul byte was not in the expected position. The slice used to create a [`CStr`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") must have one and only one nul byte, positioned at the end. This error is created by the [`CStr::from_bytes_with_nul`](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.from_bytes_with_nul "associated function std::ffi::CStr::from_bytes_with_nul") method. See its documentation for more. [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#examples) Examples ----------------------------------------------------------------------------------------------- use std::ffi::{CStr, FromBytesWithNulError}; let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::ffi::%7BCStr,+FromBytesWithNulError%7D;%0A++++%0A++++let+_:+FromBytesWithNulError+=+CStr::from_bytes_with_nul(b%22f%5C0oo%22).unwrap_err();%0A%7D&edition=2024 "Run code") Variants[§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#variants) ----------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#variant.InteriorNul) 1.64.0 ### InteriorNul Data provided contains an interior nul byte at byte `position`. #### Fields [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#variant.InteriorNul.field.position) `position: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ` The position of the interior nul byte. [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#variant.NotNulTerminated) 1.64.0 ### NotNulTerminated Data provided is not nul terminated. Trait Implementations[§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#trait-implementations) ------------------------------------------------------------------------------------------------------------------------- 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Clone-for-FromBytesWithNulError) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Debug-for-FromBytesWithNulError) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.17.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#138) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Display-for-FromBytesWithNulError) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#139) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.17.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#150) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Error-for-FromBytesWithNulError) ### impl [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#111) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.source) #### fn [source](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&(dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") + 'static)> Returns the lower-level source of this error, if any. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#137) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.description) #### fn [description](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#147) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.cause) #### fn [cause](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.cause) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") \> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#210) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.provide) #### fn [provide](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) <'a>(&'a self, request: &mut [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") <'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301) ) Provides type-based access to context intended for error reports. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-PartialEq-for-FromBytesWithNulError) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Copy-for-FromBytesWithNulError) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Eq-for-FromBytesWithNulError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-StructuralPartialEq-for-FromBytesWithNulError) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#synthetic-implementations) ---------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Freeze-for-FromBytesWithNulError) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-RefUnwindSafe-for-FromBytesWithNulError) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Send-for-FromBytesWithNulError) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Sync-for-FromBytesWithNulError) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Unpin-for-FromBytesWithNulError) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-UnwindSafe-for-FromBytesWithNulError) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#blanket-implementations) ----------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Char in std::ascii - Rust [Char](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[ascii](https://doc.rust-lang.org/stable/std/ascii/index.html) Enum Char Copy item path ======================== [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#61) #[repr(u8)]pub enum Char { Show 128 variants Null = 0, StartOfHeading = 1, StartOfText = 2, EndOfText = 3, EndOfTransmission = 4, Enquiry = 5, Acknowledge = 6, Bell = 7, Backspace = 8, CharacterTabulation = 9, LineFeed = 10, LineTabulation = 11, FormFeed = 12, CarriageReturn = 13, ShiftOut = 14, ShiftIn = 15, DataLinkEscape = 16, DeviceControlOne = 17, DeviceControlTwo = 18, DeviceControlThree = 19, DeviceControlFour = 20, NegativeAcknowledge = 21, SynchronousIdle = 22, EndOfTransmissionBlock = 23, Cancel = 24, EndOfMedium = 25, Substitute = 26, Escape = 27, InformationSeparatorFour = 28, InformationSeparatorThree = 29, InformationSeparatorTwo = 30, InformationSeparatorOne = 31, Space = 32, ExclamationMark = 33, QuotationMark = 34, NumberSign = 35, DollarSign = 36, PercentSign = 37, Ampersand = 38, Apostrophe = 39, LeftParenthesis = 40, RightParenthesis = 41, Asterisk = 42, PlusSign = 43, Comma = 44, HyphenMinus = 45, FullStop = 46, Solidus = 47, Digit0 = 48, Digit1 = 49, Digit2 = 50, Digit3 = 51, Digit4 = 52, Digit5 = 53, Digit6 = 54, Digit7 = 55, Digit8 = 56, Digit9 = 57, Colon = 58, Semicolon = 59, LessThanSign = 60, EqualsSign = 61, GreaterThanSign = 62, QuestionMark = 63, CommercialAt = 64, CapitalA = 65, CapitalB = 66, CapitalC = 67, CapitalD = 68, CapitalE = 69, CapitalF = 70, CapitalG = 71, CapitalH = 72, CapitalI = 73, CapitalJ = 74, CapitalK = 75, CapitalL = 76, CapitalM = 77, CapitalN = 78, CapitalO = 79, CapitalP = 80, CapitalQ = 81, CapitalR = 82, CapitalS = 83, CapitalT = 84, CapitalU = 85, CapitalV = 86, CapitalW = 87, CapitalX = 88, CapitalY = 89, CapitalZ = 90, LeftSquareBracket = 91, ReverseSolidus = 92, RightSquareBracket = 93, CircumflexAccent = 94, LowLine = 95, GraveAccent = 96, SmallA = 97, SmallB = 98, SmallC = 99, SmallD = 100, SmallE = 101, SmallF = 102, SmallG = 103, SmallH = 104, SmallI = 105, SmallJ = 106, SmallK = 107, SmallL = 108, SmallM = 109, SmallN = 110, SmallO = 111, SmallP = 112, SmallQ = 113, SmallR = 114, SmallS = 115, SmallT = 116, SmallU = 117, SmallV = 118, SmallW = 119, SmallX = 120, SmallY = 121, SmallZ = 122, LeftCurlyBracket = 123, VerticalLine = 124, RightCurlyBracket = 125, Tilde = 126, Delete = 127, } 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Expand description One of the 128 Unicode characters from U+0000 through U+007F, often known as the [ASCII](https://www.unicode.org/glossary/index.html#ASCII) subset. Officially, this is the first [block](https://www.unicode.org/glossary/index.html#block) in Unicode, _Basic Latin_. For details, see the [_C0 Controls and Basic Latin_](https://www.unicode.org/charts/PDF/U0000.pdf) code chart. This block was based on older 7-bit character code standards such as ANSI X3.4-1977, ISO 646-1973, and [NIST FIPS 1-2](https://nvlpubs.nist.gov/nistpubs/Legacy/FIPS/fipspub1-2-1977.pdf) . [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#when-to-use-this) When to use this ------------------------------------------------------------------------------------------------ The main advantage of this subset is that it’s always valid UTF-8. As such, the `&[ascii::Char]` -> `&str` conversion function (as well as other related ones) are O(1): _no_ runtime checks are needed. If you’re consuming strings, you should usually handle Unicode and thus accept `str`s, not limit yourself to `ascii::Char`s. However, certain formats are intentionally designed to produce ASCII-only output in order to be 8-bit-clean. In those cases, it can be simpler and faster to generate `ascii::Char`s instead of dealing with the variable width properties of general UTF-8 encoded strings, while still allowing the result to be used freely with other Rust things that deal in general `str`s. For example, a UUID library might offer a way to produce the string representation of a UUID as an `[ascii::Char; 36]` to avoid memory allocation yet still allow it to be used as UTF-8 via `as_str` without paying for validation (or needing `unsafe` code) the way it would if it were provided as a `[u8; 36]`. [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#layout-1) Layout ------------------------------------------------------------------------------ This type is guaranteed to have a size and alignment of 1 byte. [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#names) Names -------------------------------------------------------------------------- The variants on this type are [Unicode names](https://www.unicode.org/Public/15.0.0/ucd/NamesList.txt) of the characters in upper camel case, with a few tweaks: * For `` characters, the primary alias name is used. * `LATIN` is dropped, as this block has no non-latin letters. * `LETTER` is dropped, as `CAPITAL`/`SMALL` suffices in this block. * `DIGIT`s use a single digit rather than writing out `ZERO`, `ONE`, etc. Variants[§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variants) -------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Null) ### Null = 0 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0000 (The default variant) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.StartOfHeading) ### StartOfHeading = 1 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0001 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.StartOfText) ### StartOfText = 2 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0002 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.EndOfText) ### EndOfText = 3 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0003 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.EndOfTransmission) ### EndOfTransmission = 4 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0004 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Enquiry) ### Enquiry = 5 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0005 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Acknowledge) ### Acknowledge = 6 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0006 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Bell) ### Bell = 7 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0007 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Backspace) ### Backspace = 8 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0008 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CharacterTabulation) ### CharacterTabulation = 9 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0009 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LineFeed) ### LineFeed = 10 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+000A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LineTabulation) ### LineTabulation = 11 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+000B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.FormFeed) ### FormFeed = 12 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+000C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CarriageReturn) ### CarriageReturn = 13 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+000D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.ShiftOut) ### ShiftOut = 14 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+000E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.ShiftIn) ### ShiftIn = 15 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+000F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.DataLinkEscape) ### DataLinkEscape = 16 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0010 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.DeviceControlOne) ### DeviceControlOne = 17 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0011 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.DeviceControlTwo) ### DeviceControlTwo = 18 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0012 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.DeviceControlThree) ### DeviceControlThree = 19 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0013 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.DeviceControlFour) ### DeviceControlFour = 20 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0014 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.NegativeAcknowledge) ### NegativeAcknowledge = 21 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0015 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SynchronousIdle) ### SynchronousIdle = 22 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0016 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.EndOfTransmissionBlock) ### EndOfTransmissionBlock = 23 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0017 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Cancel) ### Cancel = 24 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0018 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.EndOfMedium) ### EndOfMedium = 25 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0019 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Substitute) ### Substitute = 26 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+001A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Escape) ### Escape = 27 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+001B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.InformationSeparatorFour) ### InformationSeparatorFour = 28 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+001C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.InformationSeparatorThree) ### InformationSeparatorThree = 29 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+001D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.InformationSeparatorTwo) ### InformationSeparatorTwo = 30 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+001E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.InformationSeparatorOne) ### InformationSeparatorOne = 31 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+001F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Space) ### Space = 32 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0020 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.ExclamationMark) ### ExclamationMark = 33 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0021 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.QuotationMark) ### QuotationMark = 34 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0022 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.NumberSign) ### NumberSign = 35 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0023 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.DollarSign) ### DollarSign = 36 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0024 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.PercentSign) ### PercentSign = 37 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0025 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Ampersand) ### Ampersand = 38 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0026 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Apostrophe) ### Apostrophe = 39 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0027 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LeftParenthesis) ### LeftParenthesis = 40 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0028 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.RightParenthesis) ### RightParenthesis = 41 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0029 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Asterisk) ### Asterisk = 42 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+002A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.PlusSign) ### PlusSign = 43 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+002B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Comma) ### Comma = 44 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+002C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.HyphenMinus) ### HyphenMinus = 45 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+002D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.FullStop) ### FullStop = 46 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+002E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Solidus) ### Solidus = 47 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+002F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit0) ### Digit0 = 48 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0030 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit1) ### Digit1 = 49 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0031 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit2) ### Digit2 = 50 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0032 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit3) ### Digit3 = 51 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0033 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit4) ### Digit4 = 52 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0034 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit5) ### Digit5 = 53 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0035 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit6) ### Digit6 = 54 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0036 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit7) ### Digit7 = 55 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0037 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit8) ### Digit8 = 56 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0038 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Digit9) ### Digit9 = 57 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0039 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Colon) ### Colon = 58 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+003A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Semicolon) ### Semicolon = 59 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+003B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LessThanSign) ### LessThanSign = 60 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+003C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.EqualsSign) ### EqualsSign = 61 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+003D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.GreaterThanSign) ### GreaterThanSign = 62 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+003E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.QuestionMark) ### QuestionMark = 63 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+003F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CommercialAt) ### CommercialAt = 64 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0040 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalA) ### CapitalA = 65 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0041 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalB) ### CapitalB = 66 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0042 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalC) ### CapitalC = 67 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0043 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalD) ### CapitalD = 68 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0044 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalE) ### CapitalE = 69 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0045 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalF) ### CapitalF = 70 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0046 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalG) ### CapitalG = 71 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0047 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalH) ### CapitalH = 72 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0048 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalI) ### CapitalI = 73 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0049 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalJ) ### CapitalJ = 74 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+004A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalK) ### CapitalK = 75 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+004B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalL) ### CapitalL = 76 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+004C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalM) ### CapitalM = 77 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+004D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalN) ### CapitalN = 78 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+004E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalO) ### CapitalO = 79 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+004F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalP) ### CapitalP = 80 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0050 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalQ) ### CapitalQ = 81 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0051 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalR) ### CapitalR = 82 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0052 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalS) ### CapitalS = 83 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0053 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalT) ### CapitalT = 84 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0054 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalU) ### CapitalU = 85 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0055 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalV) ### CapitalV = 86 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0056 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalW) ### CapitalW = 87 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0057 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalX) ### CapitalX = 88 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0058 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalY) ### CapitalY = 89 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0059 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CapitalZ) ### CapitalZ = 90 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+005A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LeftSquareBracket) ### LeftSquareBracket = 91 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+005B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.ReverseSolidus) ### ReverseSolidus = 92 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+005C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.RightSquareBracket) ### RightSquareBracket = 93 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+005D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.CircumflexAccent) ### CircumflexAccent = 94 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+005E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LowLine) ### LowLine = 95 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+005F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.GraveAccent) ### GraveAccent = 96 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0060 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallA) ### SmallA = 97 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0061 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallB) ### SmallB = 98 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0062 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallC) ### SmallC = 99 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0063 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallD) ### SmallD = 100 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0064 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallE) ### SmallE = 101 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0065 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallF) ### SmallF = 102 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0066 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallG) ### SmallG = 103 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0067 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallH) ### SmallH = 104 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0068 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallI) ### SmallI = 105 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0069 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallJ) ### SmallJ = 106 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+006A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallK) ### SmallK = 107 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+006B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallL) ### SmallL = 108 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+006C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallM) ### SmallM = 109 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+006D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallN) ### SmallN = 110 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+006E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallO) ### SmallO = 111 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+006F [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallP) ### SmallP = 112 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0070 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallQ) ### SmallQ = 113 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0071 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallR) ### SmallR = 114 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0072 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallS) ### SmallS = 115 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0073 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallT) ### SmallT = 116 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0074 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallU) ### SmallU = 117 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0075 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallV) ### SmallV = 118 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0076 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallW) ### SmallW = 119 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0077 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallX) ### SmallX = 120 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0078 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallY) ### SmallY = 121 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+0079 [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.SmallZ) ### SmallZ = 122 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+007A [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.LeftCurlyBracket) ### LeftCurlyBracket = 123 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+007B [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.VerticalLine) ### VerticalLine = 124 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+007C [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.RightCurlyBracket) ### RightCurlyBracket = 125 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+007D [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Tilde) ### Tilde = 126 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+007E [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#variant.Delete) ### Delete = 127 🔬This is a nightly-only experimental API. (`ascii_char_variants` [#110998](https://github.com/rust-lang/rust/issues/110998) ) U+007F Implementations[§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#implementations) ---------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#448) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Char) ### impl [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#451) #### pub const [MIN](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#associatedconstant.MIN) : [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") = Self::Null 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) The character with the lowest ASCII code. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#455) #### pub const [MAX](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#associatedconstant.MAX) : [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") = Self::Delete 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) The character with the highest ASCII code. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#461) #### pub const fn [from\_u8](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from_u8) (b: [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Creates an ASCII character from the byte `b`, or returns `None` if it’s too large. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#478) #### pub const unsafe fn [from\_u8\_unchecked](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from_u8_unchecked) (b: [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Creates an ASCII character from the byte `b`, without checking whether it’s valid. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#safety) Safety `b` must be in `0..=127`, or else this is UB. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#489) #### pub const fn [digit](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.digit) (d: [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) When passed the _number_ `0`, `1`, …, `9`, returns the _character_ `'0'`, `'1'`, …, `'9'` respectively. If `d >= 10`, returns `None`. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#516) #### pub const unsafe fn [digit\_unchecked](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.digit_unchecked) (d: [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) When passed the _number_ `0`, `1`, …, `9`, returns the _character_ `'0'`, `'1'`, …, `'9'` respectively, without checking that it’s in-range. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#safety-1) Safety This is immediate UB if called with `d > 64`. If `d >= 10` and `d <= 64`, this is allowed to return any value or panic. Notably, it should not be expected to return hex digits, or any other reasonable extension of the decimal digits. (This loose safety condition is intended to simplify soundness proofs when writing code using this method, since the implementation doesn’t need something really specific, not to make those other arguments do something useful. It might be tightened before stabilization.) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#535) #### pub const fn [to\_u8](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_u8) (self) -> [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Gets this ASCII character as a byte. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#542) #### pub const fn [to\_char](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_char) (self) -> [char](https://doc.rust-lang.org/stable/std/primitive.char.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Gets this ASCII character as a `char` Unicode Scalar Value. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#549) #### pub const fn [as\_str](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.as_str) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Views this ASCII character as a one-code-unit UTF-8 `str`. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#577) #### pub const fn [to\_uppercase](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_uppercase) (self) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Makes a copy of the value in its upper case equivalent. Letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’. To uppercase the value in-place, use [`make_uppercase`](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.make_uppercase "method std::ascii::Char::make_uppercase") . ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let lowercase_a = ascii::Char::SmallA; assert_eq!( ascii::Char::CapitalA, lowercase_a.to_uppercase(), ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+lowercase_a+=+ascii::Char::SmallA;%0A++++%0A++++assert_eq!(%0A++++++++ascii::Char::CapitalA,%0A++++++++lowercase_a.to_uppercase(),%0A++++);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#607) #### pub const fn [to\_lowercase](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_lowercase) (self) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Makes a copy of the value in its lower case equivalent. Letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’. To lowercase the value in-place, use [`make_lowercase`](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.make_lowercase "method std::ascii::Char::make_lowercase") . ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-1) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; assert_eq!( ascii::Char::SmallA, uppercase_a.to_lowercase(), ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++%0A++++assert_eq!(%0A++++++++ascii::Char::SmallA,%0A++++++++uppercase_a.to_lowercase(),%0A++++);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#630) #### pub const fn [eq\_ignore\_case](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.eq_ignore_case) (self, other: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks that two values are a case-insensitive match. This is equivalent to `to_lowercase(a) == to_lowercase(b)`. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-2) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let lowercase_a = ascii::Char::SmallA; let uppercase_a = ascii::Char::CapitalA; assert!(lowercase_a.eq_ignore_case(uppercase_a)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+lowercase_a+=+ascii::Char::SmallA;%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++%0A++++assert!(lowercase_a.eq_ignore_case(uppercase_a));%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#659) #### pub const fn [make\_uppercase](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.make_uppercase) (&mut self) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Converts this value to its upper case equivalent in-place. Letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’. To return a new uppercased value without modifying the existing one, use [`to_uppercase`](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_uppercase "method std::ascii::Char::to_uppercase") . ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-3) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let mut letter_a = ascii::Char::SmallA; letter_a.make_uppercase(); assert_eq!(ascii::Char::CapitalA, letter_a); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+mut+letter_a+=+ascii::Char::SmallA;%0A++++%0A++++letter_a.make_uppercase();%0A++++%0A++++assert_eq!(ascii::Char::CapitalA,+letter_a);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#686) #### pub const fn [make\_lowercase](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.make_lowercase) (&mut self) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Converts this value to its lower case equivalent in-place. Letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’. To return a new lowercased value without modifying the existing one, use [`to_lowercase`](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_lowercase "method std::ascii::Char::to_lowercase") . ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-4) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let mut letter_a = ascii::Char::CapitalA; letter_a.make_lowercase(); assert_eq!(ascii::Char::SmallA, letter_a); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+mut+letter_a+=+ascii::Char::CapitalA;%0A++++%0A++++letter_a.make_lowercase();%0A++++%0A++++assert_eq!(ascii::Char::SmallA,+letter_a);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#724) #### pub const fn [is\_alphabetic](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_alphabetic) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is an alphabetic character: * 0x41 ‘A’ ..= 0x5A ‘Z’, or * 0x61 ‘a’ ..= 0x7A ‘z’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-5) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(uppercase_a.is_alphabetic()); assert!(uppercase_g.is_alphabetic()); assert!(a.is_alphabetic()); assert!(g.is_alphabetic()); assert!(!zero.is_alphabetic()); assert!(!percent.is_alphabetic()); assert!(!space.is_alphabetic()); assert!(!lf.is_alphabetic()); assert!(!esc.is_alphabetic()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(uppercase_a.is_alphabetic());%0A++++assert!(uppercase_g.is_alphabetic());%0A++++assert!(a.is_alphabetic());%0A++++assert!(g.is_alphabetic());%0A++++assert!(!zero.is_alphabetic());%0A++++assert!(!percent.is_alphabetic());%0A++++assert!(!space.is_alphabetic());%0A++++assert!(!lf.is_alphabetic());%0A++++assert!(!esc.is_alphabetic());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#760) #### pub const fn [is\_uppercase](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_uppercase) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is an uppercase character: 0x41 ‘A’ ..= 0x5A ‘Z’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-6) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(uppercase_a.is_uppercase()); assert!(uppercase_g.is_uppercase()); assert!(!a.is_uppercase()); assert!(!g.is_uppercase()); assert!(!zero.is_uppercase()); assert!(!percent.is_uppercase()); assert!(!space.is_uppercase()); assert!(!lf.is_uppercase()); assert!(!esc.is_uppercase()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(uppercase_a.is_uppercase());%0A++++assert!(uppercase_g.is_uppercase());%0A++++assert!(!a.is_uppercase());%0A++++assert!(!g.is_uppercase());%0A++++assert!(!zero.is_uppercase());%0A++++assert!(!percent.is_uppercase());%0A++++assert!(!space.is_uppercase());%0A++++assert!(!lf.is_uppercase());%0A++++assert!(!esc.is_uppercase());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#796) #### pub const fn [is\_lowercase](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_lowercase) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a lowercase character: 0x61 ‘a’ ..= 0x7A ‘z’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-7) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(!uppercase_a.is_lowercase()); assert!(!uppercase_g.is_lowercase()); assert!(a.is_lowercase()); assert!(g.is_lowercase()); assert!(!zero.is_lowercase()); assert!(!percent.is_lowercase()); assert!(!space.is_lowercase()); assert!(!lf.is_lowercase()); assert!(!esc.is_lowercase()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(!uppercase_a.is_lowercase());%0A++++assert!(!uppercase_g.is_lowercase());%0A++++assert!(a.is_lowercase());%0A++++assert!(g.is_lowercase());%0A++++assert!(!zero.is_lowercase());%0A++++assert!(!percent.is_lowercase());%0A++++assert!(!space.is_lowercase());%0A++++assert!(!lf.is_lowercase());%0A++++assert!(!esc.is_lowercase());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#835) #### pub const fn [is\_alphanumeric](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_alphanumeric) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is an alphanumeric character: * 0x41 ‘A’ ..= 0x5A ‘Z’, or * 0x61 ‘a’ ..= 0x7A ‘z’, or * 0x30 ‘0’ ..= 0x39 ‘9’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-8) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(uppercase_a.is_alphanumeric()); assert!(uppercase_g.is_alphanumeric()); assert!(a.is_alphanumeric()); assert!(g.is_alphanumeric()); assert!(zero.is_alphanumeric()); assert!(!percent.is_alphanumeric()); assert!(!space.is_alphanumeric()); assert!(!lf.is_alphanumeric()); assert!(!esc.is_alphanumeric()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(uppercase_a.is_alphanumeric());%0A++++assert!(uppercase_g.is_alphanumeric());%0A++++assert!(a.is_alphanumeric());%0A++++assert!(g.is_alphanumeric());%0A++++assert!(zero.is_alphanumeric());%0A++++assert!(!percent.is_alphanumeric());%0A++++assert!(!space.is_alphanumeric());%0A++++assert!(!lf.is_alphanumeric());%0A++++assert!(!esc.is_alphanumeric());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#871) #### pub const fn [is\_digit](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_digit) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a decimal digit: 0x30 ‘0’ ..= 0x39 ‘9’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-9) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(!uppercase_a.is_digit()); assert!(!uppercase_g.is_digit()); assert!(!a.is_digit()); assert!(!g.is_digit()); assert!(zero.is_digit()); assert!(!percent.is_digit()); assert!(!space.is_digit()); assert!(!lf.is_digit()); assert!(!esc.is_digit()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(!uppercase_a.is_digit());%0A++++assert!(!uppercase_g.is_digit());%0A++++assert!(!a.is_digit());%0A++++assert!(!g.is_digit());%0A++++assert!(zero.is_digit());%0A++++assert!(!percent.is_digit());%0A++++assert!(!space.is_digit());%0A++++assert!(!lf.is_digit());%0A++++assert!(!esc.is_digit());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#909) #### pub const fn [is\_octdigit](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_octdigit) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is an octal digit: 0x30 ‘0’ ..= 0x37 ‘7’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-10) Examples #![feature(ascii_char, ascii_char_variants, is_ascii_octdigit)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let a = ascii::Char::SmallA; let zero = ascii::Char::Digit0; let seven = ascii::Char::Digit7; let eight = ascii::Char::Digit8; let percent = ascii::Char::PercentSign; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(!uppercase_a.is_octdigit()); assert!(!a.is_octdigit()); assert!(zero.is_octdigit()); assert!(seven.is_octdigit()); assert!(!eight.is_octdigit()); assert!(!percent.is_octdigit()); assert!(!lf.is_octdigit()); assert!(!esc.is_octdigit()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants,+is_ascii_octdigit)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+seven+=+ascii::Char::Digit7;%0A++++let+eight+=+ascii::Char::Digit8;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(!uppercase_a.is_octdigit());%0A++++assert!(!a.is_octdigit());%0A++++assert!(zero.is_octdigit());%0A++++assert!(seven.is_octdigit());%0A++++assert!(!eight.is_octdigit());%0A++++assert!(!percent.is_octdigit());%0A++++assert!(!lf.is_octdigit());%0A++++assert!(!esc.is_octdigit());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#948) #### pub const fn [is\_hexdigit](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_hexdigit) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a hexadecimal digit: * 0x30 ‘0’ ..= 0x39 ‘9’, or * 0x41 ‘A’ ..= 0x46 ‘F’, or * 0x61 ‘a’ ..= 0x66 ‘f’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-11) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(uppercase_a.is_hexdigit()); assert!(!uppercase_g.is_hexdigit()); assert!(a.is_hexdigit()); assert!(!g.is_hexdigit()); assert!(zero.is_hexdigit()); assert!(!percent.is_hexdigit()); assert!(!space.is_hexdigit()); assert!(!lf.is_hexdigit()); assert!(!esc.is_hexdigit()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(uppercase_a.is_hexdigit());%0A++++assert!(!uppercase_g.is_hexdigit());%0A++++assert!(a.is_hexdigit());%0A++++assert!(!g.is_hexdigit());%0A++++assert!(zero.is_hexdigit());%0A++++assert!(!percent.is_hexdigit());%0A++++assert!(!space.is_hexdigit());%0A++++assert!(!lf.is_hexdigit());%0A++++assert!(!esc.is_hexdigit());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#988) #### pub const fn [is\_punctuation](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_punctuation) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a punctuation character: * 0x21 ..= 0x2F `! " # $ % & ' ( ) * + , - . /`, or * 0x3A ..= 0x40 `: ; < = > ? @`, or * 0x5B ..= 0x60 `` [ \ ] ^ _ ` ``, or * 0x7B ..= 0x7E `{ | } ~` ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-12) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(!uppercase_a.is_punctuation()); assert!(!uppercase_g.is_punctuation()); assert!(!a.is_punctuation()); assert!(!g.is_punctuation()); assert!(!zero.is_punctuation()); assert!(percent.is_punctuation()); assert!(!space.is_punctuation()); assert!(!lf.is_punctuation()); assert!(!esc.is_punctuation()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(!uppercase_a.is_punctuation());%0A++++assert!(!uppercase_g.is_punctuation());%0A++++assert!(!a.is_punctuation());%0A++++assert!(!g.is_punctuation());%0A++++assert!(!zero.is_punctuation());%0A++++assert!(percent.is_punctuation());%0A++++assert!(!space.is_punctuation());%0A++++assert!(!lf.is_punctuation());%0A++++assert!(!esc.is_punctuation());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1024) #### pub const fn [is\_graphic](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_graphic) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a graphic character: 0x21 ‘!’ ..= 0x7E ‘~’. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-13) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(uppercase_a.is_graphic()); assert!(uppercase_g.is_graphic()); assert!(a.is_graphic()); assert!(g.is_graphic()); assert!(zero.is_graphic()); assert!(percent.is_graphic()); assert!(!space.is_graphic()); assert!(!lf.is_graphic()); assert!(!esc.is_graphic()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(uppercase_a.is_graphic());%0A++++assert!(uppercase_g.is_graphic());%0A++++assert!(a.is_graphic());%0A++++assert!(g.is_graphic());%0A++++assert!(zero.is_graphic());%0A++++assert!(percent.is_graphic());%0A++++assert!(!space.is_graphic());%0A++++assert!(!lf.is_graphic());%0A++++assert!(!esc.is_graphic());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1077) #### pub const fn [is\_whitespace](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_whitespace) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a whitespace character: 0x20 SPACE, 0x09 HORIZONTAL TAB, 0x0A LINE FEED, 0x0C FORM FEED, or 0x0D CARRIAGE RETURN. Rust uses the WhatWG Infra Standard’s [definition of ASCII whitespace](https://infra.spec.whatwg.org/#ascii-whitespace) . There are several other definitions in wide use. For instance, [the POSIX locale](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01) includes 0x0B VERTICAL TAB as well as all the above characters, but—from the very same specification—[the default rule for “field splitting” in the Bourne shell](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05) considers _only_ SPACE, HORIZONTAL TAB, and LINE FEED as whitespace. If you are writing a program that will process an existing file format, check what that format’s definition of whitespace is before using this function. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-14) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(!uppercase_a.is_whitespace()); assert!(!uppercase_g.is_whitespace()); assert!(!a.is_whitespace()); assert!(!g.is_whitespace()); assert!(!zero.is_whitespace()); assert!(!percent.is_whitespace()); assert!(space.is_whitespace()); assert!(lf.is_whitespace()); assert!(!esc.is_whitespace()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(!uppercase_a.is_whitespace());%0A++++assert!(!uppercase_g.is_whitespace());%0A++++assert!(!a.is_whitespace());%0A++++assert!(!g.is_whitespace());%0A++++assert!(!zero.is_whitespace());%0A++++assert!(!percent.is_whitespace());%0A++++assert!(space.is_whitespace());%0A++++assert!(lf.is_whitespace());%0A++++assert!(!esc.is_whitespace());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1115) #### pub const fn [is\_control](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.is_control) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Checks if the value is a control character: 0x00 NUL ..= 0x1F UNIT SEPARATOR, or 0x7F DELETE. Note that most whitespace characters are control characters, but SPACE is not. ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-15) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let uppercase_a = ascii::Char::CapitalA; let uppercase_g = ascii::Char::CapitalG; let a = ascii::Char::SmallA; let g = ascii::Char::SmallG; let zero = ascii::Char::Digit0; let percent = ascii::Char::PercentSign; let space = ascii::Char::Space; let lf = ascii::Char::LineFeed; let esc = ascii::Char::Escape; assert!(!uppercase_a.is_control()); assert!(!uppercase_g.is_control()); assert!(!a.is_control()); assert!(!g.is_control()); assert!(!zero.is_control()); assert!(!percent.is_control()); assert!(!space.is_control()); assert!(lf.is_control()); assert!(esc.is_control()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+uppercase_a+=+ascii::Char::CapitalA;%0A++++let+uppercase_g+=+ascii::Char::CapitalG;%0A++++let+a+=+ascii::Char::SmallA;%0A++++let+g+=+ascii::Char::SmallG;%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+percent+=+ascii::Char::PercentSign;%0A++++let+space+=+ascii::Char::Space;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+esc+=+ascii::Char::Escape;%0A++++%0A++++assert!(!uppercase_a.is_control());%0A++++assert!(!uppercase_g.is_control());%0A++++assert!(!a.is_control());%0A++++assert!(!g.is_control());%0A++++assert!(!zero.is_control());%0A++++assert!(!percent.is_control());%0A++++assert!(!space.is_control());%0A++++assert!(lf.is_control());%0A++++assert!(esc.is_control());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1151) #### pub fn [escape\_ascii](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.escape_ascii) (self) -> [EscapeDefault](https://doc.rust-lang.org/stable/std/ascii/struct.EscapeDefault.html "struct std::ascii::EscapeDefault") [ⓘ](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#) 🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998) ) Returns an iterator that produces an escaped version of a character. The behavior is identical to [`ascii::escape_default`](https://doc.rust-lang.org/stable/std/ascii/fn.escape_default.html "fn std::ascii::escape_default") . ##### [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#examples-16) Examples #![feature(ascii_char, ascii_char_variants)] use std::ascii; let zero = ascii::Char::Digit0; let tab = ascii::Char::CharacterTabulation; let cr = ascii::Char::CarriageReturn; let lf = ascii::Char::LineFeed; let apostrophe = ascii::Char::Apostrophe; let double_quote = ascii::Char::QuotationMark; let backslash = ascii::Char::ReverseSolidus; assert_eq!("0", zero.escape_ascii().to_string()); assert_eq!("\\t", tab.escape_ascii().to_string()); assert_eq!("\\r", cr.escape_ascii().to_string()); assert_eq!("\\n", lf.escape_ascii().to_string()); assert_eq!("\\'", apostrophe.escape_ascii().to_string()); assert_eq!("\\\"", double_quote.escape_ascii().to_string()); assert_eq!("\\\\", backslash.escape_ascii().to_string()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ascii_char,+ascii_char_variants)%5D%0A%0Afn+main()+%7B%0A++++use+std::ascii;%0A++++%0A++++let+zero+=+ascii::Char::Digit0;%0A++++let+tab+=+ascii::Char::CharacterTabulation;%0A++++let+cr+=+ascii::Char::CarriageReturn;%0A++++let+lf+=+ascii::Char::LineFeed;%0A++++let+apostrophe+=+ascii::Char::Apostrophe;%0A++++let+double_quote+=+ascii::Char::QuotationMark;%0A++++let+backslash+=+ascii::Char::ReverseSolidus;%0A++++%0A++++assert_eq!(%220%22,+zero.escape_ascii().to_string());%0A++++assert_eq!(%22%5C%5Ct%22,+tab.escape_ascii().to_string());%0A++++assert_eq!(%22%5C%5Cr%22,+cr.escape_ascii().to_string());%0A++++assert_eq!(%22%5C%5Cn%22,+lf.escape_ascii().to_string());%0A++++assert_eq!(%22%5C%5C%27%22,+apostrophe.escape_ascii().to_string());%0A++++assert_eq!(%22%5C%5C%5C%22%22,+double_quote.escape_ascii().to_string());%0A++++assert_eq!(%22%5C%5C%5C%5C%22,+backslash.escape_ascii().to_string());%0A%7D&version=nightly&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#trait-implementations) ---------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Clone-for-Char) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1201) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Debug-for-Char) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1202) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143894 "Tracking issue for const_default") ) · [Source](https://doc.rust-lang.org/stable/src/core/default.rs.html#167) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Default-for-Char) ### impl [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/default.rs.html#167) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.default) #### fn [default](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default) () -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") Returns the default value of `Null` [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1194) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Display-for-Char) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1195) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2566) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Extend%3C%26Char%3E-for-String) ### impl<'a> [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") <&'a [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2568) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.extend-1) #### fn [extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) (&mut self, iter: I) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Extends a collection with the contents of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2573) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.extend_one-1) #### fn [extend\_one](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_one) (&mut self, c: &'a [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Extends a collection with exactly one element. [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#425) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.extend_reserve-1) #### fn [extend\_reserve](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Reserves capacity in a collection for the given number of additional elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2552) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Extend%3CChar%3E-for-String) ### impl [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2554) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.extend) #### fn [extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) (&mut self, iter: I) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Extends a collection with the contents of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2559) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.extend_one) #### fn [extend\_one](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_one) (&mut self, c: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Extends a collection with exactly one element. [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#425) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.extend_reserve) #### fn [extend\_reserve](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Reserves capacity in a collection for the given number of additional elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CChar%3E-for-char) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [char](https://doc.rust-lang.org/stable/std/primitive.char.html) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from-5) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (chr: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [char](https://doc.rust-lang.org/stable/std/primitive.char.html) Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CChar%3E-for-u128) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from-4) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (chr: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CChar%3E-for-u16) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (chr: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CChar%3E-for-u32) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from-2) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (chr: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CChar%3E-for-u64) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from-3) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (chr: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CChar%3E-for-u8) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (chr: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) Converts to this type from the input type. [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2455) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-FromIterator%3C%26Char%3E-for-String) ### impl<'a> [FromIterator](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html "trait std::iter::FromIterator") <&'a [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2456) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from_iter-1) #### fn [from\_iter](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) (iter: T) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") where T: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Creates a value from an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#3272) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-FromIterator%3CChar%3E-for-Cow%3C'a,+str%3E) ### impl<'a> [FromIterator](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html "trait std::iter::FromIterator") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#3273) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from_iter-2) #### fn [from\_iter](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) (it: T) -> [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> where T: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Creates a value from an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2444) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-FromIterator%3CChar%3E-for-String) ### impl [FromIterator](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html "trait std::iter::FromIterator") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2445) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from_iter) #### fn [from\_iter](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) (iter: T) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") where T: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Creates a value from an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#57) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Hash-for-Char) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#57) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where \_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Ord-for-Char) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.cmp) #### fn [cmp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) (&self, other: &[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") This method returns an [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") between `self` and `other`. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1021-1023) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.max) #### fn [max](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the maximum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1060-1062) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.min) #### fn [min](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the minimum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1086-1088) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.clamp) #### fn [clamp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (self, min: Self, max: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Restrict a value to a certain interval. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-PartialEq-for-Char) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-PartialOrd-for-Char) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.partial_cmp) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.lt) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.le) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.gt) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.ge) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#532) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Step-for-Char) ### impl [Step](https://doc.rust-lang.org/stable/std/iter/trait.Step.html "trait std::iter::Step") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#534) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.steps_between) #### fn [steps\_between](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#tymethod.steps_between) (\_: &[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") , \_: &[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") ) -> ([usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) , [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) \>) 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the bounds on the number of _successor_ steps required to get from `start` to `end` like [`Iterator::size_hint()`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint "method std::iter::Iterator::size_hint") . [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#tymethod.steps_between) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#539) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.forward_checked) #### fn [forward\_checked](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#tymethod.forward_checked) (start: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") , count: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the value that would be obtained by taking the _successor_ of `self` `count` times. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#tymethod.forward_checked) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#545) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.backward_checked) #### fn [backward\_checked](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#tymethod.backward_checked) (start: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") , count: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") \> 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the value that would be obtained by taking the _predecessor_ of `self` `count` times. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#tymethod.backward_checked) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#553) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.forward_unchecked) #### unsafe fn [forward\_unchecked](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.forward_unchecked) (start: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") , count: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the value that would be obtained by taking the _successor_ of `self` `count` times. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.forward_unchecked) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#563) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.backward_unchecked) #### unsafe fn [backward\_unchecked](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.backward_unchecked) (start: [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") , count: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the value that would be obtained by taking the _predecessor_ of `self` `count` times. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.backward_unchecked) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#83) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.forward) #### fn [forward](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.forward) (start: Self, count: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> Self 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the value that would be obtained by taking the _successor_ of `self` `count` times. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.forward) [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#153) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.backward) #### fn [backward](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.backward) (start: Self, count: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> Self 🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168) ) Returns the value that would be obtained by taking the _predecessor_ of `self` `count` times. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Step.html#method.backward) [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#57) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Copy-for-Char) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Eq-for-Char) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-StructuralPartialEq-for-Char) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [Source](https://doc.rust-lang.org/stable/src/core/iter/range.rs.html#17) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-TrustedStep-for-Char) ### impl [TrustedStep](https://doc.rust-lang.org/stable/std/iter/trait.TrustedStep.html "trait std::iter::TrustedStep") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Freeze-for-Char) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-RefUnwindSafe-for-Char) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Send-for-Char) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Sync-for-Char) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Unpin-for-Char) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-UnwindSafe-for-Char) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#blanket-implementations) -------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.from-6) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # SearchStep in std::str::pattern - Rust [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#) ------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[str](https://doc.rust-lang.org/stable/std/str/index.html) ::[pattern](https://doc.rust-lang.org/stable/std/str/pattern/index.html) Enum SearchStep Copy item path ============================== [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#185) pub enum SearchStep { Match(usize, usize), Reject(usize, usize), Done, } 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721) ) Expand description Result of calling [`Searcher::next()`](https://doc.rust-lang.org/stable/std/str/pattern/trait.Searcher.html#tymethod.next "method std::str::pattern::Searcher::next") or [`ReverseSearcher::next_back()`](https://doc.rust-lang.org/stable/std/str/pattern/trait.ReverseSearcher.html#tymethod.next_back "method std::str::pattern::ReverseSearcher::next_back") . Variants[§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#variants) -------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#variant.Match) ### Match([usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) , [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721) ) Expresses that a match of the pattern has been found at `haystack[a..b]`. [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#variant.Reject) ### Reject([usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) , [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721) ) Expresses that `haystack[a..b]` has been rejected as a possible match of the pattern. Note that there might be more than one `Reject` between two `Match`es, there is no requirement for them to be combined into one. [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#variant.Done) ### Done 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721) ) Expresses that every byte of the haystack has been visited, ending the iteration. Trait Implementations[§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#trait-implementations) ---------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Clone-for-SearchStep) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Debug-for-SearchStep) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-PartialEq-for-SearchStep) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Copy-for-SearchStep) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Eq-for-SearchStep) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-StructuralPartialEq-for-SearchStep) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Freeze-for-SearchStep) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-RefUnwindSafe-for-SearchStep) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Send-for-SearchStep) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Sync-for-SearchStep) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Unpin-for-SearchStep) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-UnwindSafe-for-SearchStep) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#blanket-implementations) -------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Ipv6MulticastScope in std::net - Rust [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#) --------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[net](https://doc.rust-lang.org/stable/std/net/index.html) Enum Ipv6MulticastScope Copy item path ====================================== [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#218) #[non_exhaustive]pub enum Ipv6MulticastScope { InterfaceLocal, LinkLocal, RealmLocal, AdminLocal, SiteLocal, OrganizationLocal, Global, } 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Expand description Scope of an [IPv6 multicast address](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") as defined in [IETF RFC 7346 section 2](https://tools.ietf.org/html/rfc7346#section-2) . [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#stability-guarantees) Stability Guarantees -------------------------------------------------------------------------------------------------------------------- Not all possible values for a multicast scope have been assigned. Future RFCs may introduce new scopes, which will be added as variants to this enum; because of this the enum is marked as `#[non_exhaustive]`. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#examples) Examples -------------------------------------------------------------------------------------------- #![feature(ip)] use std::net::Ipv6Addr; use std::net::Ipv6MulticastScope::*; // An IPv6 multicast address with global scope (`ff0e::`). let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0); // Will print "Global scope". match address.multicast_scope() { Some(InterfaceLocal) => println!("Interface-Local scope"), Some(LinkLocal) => println!("Link-Local scope"), Some(RealmLocal) => println!("Realm-Local scope"), Some(AdminLocal) => println!("Admin-Local scope"), Some(SiteLocal) => println!("Site-Local scope"), Some(OrganizationLocal) => println!("Organization-Local scope"), Some(Global) => println!("Global scope"), Some(_) => println!("Unknown scope"), None => println!("Not a multicast address!") } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ip)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::net::Ipv6Addr;%0A++++use+std::net::Ipv6MulticastScope::*;%0A++++%0A++++//+An+IPv6+multicast+address+with+global+scope+(%60ff0e::%60).%0A++++let+address+=+Ipv6Addr::new(0xff0e,+0,+0,+0,+0,+0,+0,+0);%0A++++%0A++++//+Will+print+%22Global+scope%22.%0A++++match+address.multicast_scope()+%7B%0A++++++++Some(InterfaceLocal)+=%3E+println!(%22Interface-Local+scope%22),%0A++++++++Some(LinkLocal)+=%3E+println!(%22Link-Local+scope%22),%0A++++++++Some(RealmLocal)+=%3E+println!(%22Realm-Local+scope%22),%0A++++++++Some(AdminLocal)+=%3E+println!(%22Admin-Local+scope%22),%0A++++++++Some(SiteLocal)+=%3E+println!(%22Site-Local+scope%22),%0A++++++++Some(OrganizationLocal)+=%3E+println!(%22Organization-Local+scope%22),%0A++++++++Some(Global)+=%3E+println!(%22Global+scope%22),%0A++++++++Some(_)+=%3E+println!(%22Unknown+scope%22),%0A++++++++None+=%3E+println!(%22Not+a+multicast+address!%22)%0A++++%7D%0A%7D&version=nightly&edition=2024 "Run code") Variants (Non-exhaustive)[§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variants) ------------------------------------------------------------------------------------------------------------- This enum is marked as non-exhaustive Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.InterfaceLocal) ### InterfaceLocal 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Interface-Local scope. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.LinkLocal) ### LinkLocal 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Link-Local scope. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.RealmLocal) ### RealmLocal 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Realm-Local scope. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.AdminLocal) ### AdminLocal 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Admin-Local scope. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.SiteLocal) ### SiteLocal 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Site-Local scope. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.OrganizationLocal) ### OrganizationLocal 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Organization-Local scope. [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#variant.Global) ### Global 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Global scope. Trait Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#trait-implementations) ---------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Clone-for-Ipv6MulticastScope) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Debug-for-Ipv6MulticastScope) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Hash-for-Ipv6MulticastScope) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where \_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-PartialEq-for-Ipv6MulticastScope) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Copy-for-Ipv6MulticastScope) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Eq-for-Ipv6MulticastScope) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-StructuralPartialEq-for-Ipv6MulticastScope) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Freeze-for-Ipv6MulticastScope) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-RefUnwindSafe-for-Ipv6MulticastScope) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Send-for-Ipv6MulticastScope) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Sync-for-Ipv6MulticastScope) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Unpin-for-Ipv6MulticastScope) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-UnwindSafe-for-Ipv6MulticastScope) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#blanket-implementations) -------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # RecvTimeoutError in std::sync::mpsc - Rust [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#) ----------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) ::[mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html) Enum RecvTimeoutError Copy item path ==================================== 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#446-455) pub enum RecvTimeoutError { Timeout, Disconnected, } Expand description This enumeration is the list of possible errors that made [`recv_timeout`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv_timeout "method std::sync::mpsc::Receiver::recv_timeout") unable to return data when called. This can occur with both a [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") and a [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") . Variants[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#variants) ------------------------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#variant.Timeout) 1.12.0 ### Timeout This **channel** is currently empty, but the **Sender**(s) have not yet disconnected, so data may yet become available. [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#variant.Disconnected) 1.12.0 ### Disconnected The **channel**’s sending half has become disconnected, and there will never be any more data received on it. Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#trait-implementations) -------------------------------------------------------------------------------------------------------------------------- 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Clone-for-RecvTimeoutError) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Debug-for-RecvTimeoutError) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.15.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1188-1195) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Display-for-RecvTimeoutError) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1189-1194) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.15.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1198) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Error-for-RecvTimeoutError) ### impl [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#111) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.source) #### fn [source](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&(dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") + 'static)> Returns the lower-level source of this error, if any. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#137) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.description) #### fn [description](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#147) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.cause) #### fn [cause](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.cause) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") \> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#210) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.provide) #### fn [provide](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) <'a>(&'a self, request: &mut [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") <'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301) ) Provides type-based access to context intended for error reports. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) 1.24.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1201-1212) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-From%3CRecvError%3E-for-RecvTimeoutError) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") \> for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1207-1211) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (err: [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") ) -> [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") Converts a `RecvError` into a `RecvTimeoutError`. This conversion always returns `RecvTimeoutError::Disconnected`. No data is allocated on the heap. 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-PartialEq-for-RecvTimeoutError) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Copy-for-RecvTimeoutError) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Eq-for-RecvTimeoutError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-StructuralPartialEq-for-RecvTimeoutError) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Freeze-for-RecvTimeoutError) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-RefUnwindSafe-for-RecvTimeoutError) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Send-for-RecvTimeoutError) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Sync-for-RecvTimeoutError) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Unpin-for-RecvTimeoutError) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-UnwindSafe-for-RecvTimeoutError) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # TryRecvError in std::sync::mpsc - Rust [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#) --------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) ::[mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html) Enum TryRecvError Copy item path ================================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#427-437) pub enum TryRecvError { Empty, Disconnected, } Expand description This enumeration is the list of the possible reasons that [`try_recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_recv "method std::sync::mpsc::Receiver::try_recv") could not return data when called. This can occur with both a [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") and a [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") . Variants[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#variants) -------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#variant.Empty) 1.0.0 ### Empty This **channel** is currently empty, but the **Sender**(s) have not yet disconnected, so data may yet become available. [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#variant.Disconnected) 1.0.0 ### Disconnected The **channel**’s sending half has become disconnected, and there will never be any more data received on it. Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#trait-implementations) ---------------------------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Clone-for-TryRecvError) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Debug-for-TryRecvError) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1161-1168) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Display-for-TryRecvError) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1162-1167) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Error-for-TryRecvError) ### impl [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#111) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.source) #### fn [source](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&(dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") + 'static)> Returns the lower-level source of this error, if any. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#137) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.description) #### fn [description](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#147) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.cause) #### fn [cause](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.cause) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") \> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#210) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.provide) #### fn [provide](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) <'a>(&'a self, request: &mut [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") <'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301) ) Provides type-based access to context intended for error reports. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) 1.24.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1174-1185) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-From%3CRecvError%3E-for-TryRecvError) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") \> for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1180-1184) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (err: [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") ) -> [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") Converts a `RecvError` into a `TryRecvError`. This conversion always returns `TryRecvError::Disconnected`. No data is allocated on the heap. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-PartialEq-for-TryRecvError) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Copy-for-TryRecvError) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Eq-for-TryRecvError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-StructuralPartialEq-for-TryRecvError) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Freeze-for-TryRecvError) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-RefUnwindSafe-for-TryRecvError) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Send-for-TryRecvError) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Sync-for-TryRecvError) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Unpin-for-TryRecvError) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-UnwindSafe-for-TryRecvError) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#blanket-implementations) -------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # IpAddr in std::net - Rust [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#) --------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[net](https://doc.rust-lang.org/stable/std/net/index.html) Enum IpAddr Copy item path ========================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#30) pub enum IpAddr { V4(Ipv4Addr), V6(Ipv6Addr), } Expand description An IP address, either IPv4 or IPv6. This enum can contain either an [`Ipv4Addr`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") or an [`Ipv6Addr`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") , see their respective documentation for more details. [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples) Examples -------------------------------------------------------------------------------- use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); assert_eq!("127.0.0.1".parse(), Ok(localhost_v4)); assert_eq!("::1".parse(), Ok(localhost_v6)); assert_eq!(localhost_v4.is_ipv6(), false); assert_eq!(localhost_v4.is_ipv4(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++let+localhost_v4+=+IpAddr::V4(Ipv4Addr::new(127,+0,+0,+1));%0A++++let+localhost_v6+=+IpAddr::V6(Ipv6Addr::new(0,+0,+0,+0,+0,+0,+0,+1));%0A++++%0A++++assert_eq!(%22127.0.0.1%22.parse(),+Ok(localhost_v4));%0A++++assert_eq!(%22::1%22.parse(),+Ok(localhost_v6));%0A++++%0A++++assert_eq!(localhost_v4.is_ipv6(),+false);%0A++++assert_eq!(localhost_v4.is_ipv4(),+true);%0A%7D&edition=2024 "Run code") Variants[§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#variants) -------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#variant.V4) 1.7.0 ### V4([Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") ) An IPv4 address. [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#variant.V6) 1.7.0 ### V6([Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") ) An IPv6 address. Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#implementations) ---------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#235) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-IpAddr) ### impl [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.12.0 (const: 1.50.0) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#253) #### pub const fn [is\_unspecified](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_unspecified) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") for the special ‘unspecified’ address. See the documentation for [`Ipv4Addr::is_unspecified()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_unspecified "method std::net::Ipv4Addr::is_unspecified") and [`Ipv6Addr::is_unspecified()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_unspecified "method std::net::Ipv6Addr::is_unspecified") for more details. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-1) Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(0,+0,+0,+0)).is_unspecified(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0,+0,+0,+0,+0,+0,+0,+0)).is_unspecified(),+true);%0A%7D&edition=2024 "Run code") 1.12.0 (const: 1.50.0) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#277) #### pub const fn [is\_loopback](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_loopback) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if this is a loopback address. See the documentation for [`Ipv4Addr::is_loopback()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_loopback "method std::net::Ipv4Addr::is_loopback") and [`Ipv6Addr::is_loopback()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_loopback "method std::net::Ipv6Addr::is_loopback") for more details. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-2) Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(127,+0,+0,+1)).is_loopback(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0,+0,+0,+0,+0,+0,+0,+0x1)).is_loopback(),+true);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#302) #### pub const fn [is\_global](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_global) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if the address appears to be globally routable. See the documentation for [`Ipv4Addr::is_global()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_global "method std::net::Ipv4Addr::is_global") and [`Ipv6Addr::is_global()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_global "method std::net::Ipv6Addr::is_global") for more details. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-3) Examples #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ip)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(80,+9,+12,+3)).is_global(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0,+0,+0x1c9,+0,+0,+0xafc8,+0,+0x1)).is_global(),+true);%0A%7D&version=nightly&edition=2024 "Run code") 1.12.0 (const: 1.50.0) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#326) #### pub const fn [is\_multicast](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_multicast) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if this is a multicast address. See the documentation for [`Ipv4Addr::is_multicast()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_multicast "method std::net::Ipv4Addr::is_multicast") and [`Ipv6Addr::is_multicast()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_multicast "method std::net::Ipv6Addr::is_multicast") for more details. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-4) Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(224,+254,+0,+0)).is_multicast(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00,+0,+0,+0,+0,+0,+0,+0)).is_multicast(),+true);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#354) #### pub const fn [is\_documentation](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_documentation) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if this address is in a range designated for documentation. See the documentation for [`Ipv4Addr::is_documentation()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_documentation "method std::net::Ipv4Addr::is_documentation") and [`Ipv6Addr::is_documentation()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_documentation "method std::net::Ipv6Addr::is_documentation") for more details. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-5) Examples #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true); assert_eq!( IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(), true ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ip)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(203,+0,+113,+6)).is_documentation(),+true);%0A++++assert_eq!(%0A++++++++IpAddr::V6(Ipv6Addr::new(0x2001,+0xdb8,+0,+0,+0,+0,+0,+0)).is_documentation(),%0A++++++++true%0A++++);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#379) #### pub const fn [is\_benchmarking](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_benchmarking) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709) ) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if this address is in a range designated for benchmarking. See the documentation for [`Ipv4Addr::is_benchmarking()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html#method.is_benchmarking "method std::net::Ipv4Addr::is_benchmarking") and [`Ipv6Addr::is_benchmarking()`](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html#method.is_benchmarking "method std::net::Ipv6Addr::is_benchmarking") for more details. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-6) Examples #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(198, 19, 255, 255)).is_benchmarking(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0)).is_benchmarking(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ip)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(198,+19,+255,+255)).is_benchmarking(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001,+0x2,+0,+0,+0,+0,+0,+0)).is_benchmarking(),+true);%0A%7D&version=nightly&edition=2024 "Run code") 1.16.0 (const: 1.50.0) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#403) #### pub const fn [is\_ipv4](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv4) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if this address is an [`IPv4` address](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#variant.V4 "variant std::net::IpAddr::V4") , and [`false`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") otherwise. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-7) Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(203,+0,+113,+6)).is_ipv4(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001,+0xdb8,+0,+0,+0,+0,+0,+0)).is_ipv4(),+false);%0A%7D&edition=2024 "Run code") 1.16.0 (const: 1.50.0) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#424) #### pub const fn [is\_ipv6](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.is_ipv6) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Returns [`true`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") if this address is an [`IPv6` address](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#variant.V6 "variant std::net::IpAddr::V6") , and [`false`](https://doc.rust-lang.org/stable/std/primitive.bool.html "primitive bool") otherwise. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-8) Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false); assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(203,+0,+113,+6)).is_ipv6(),+false);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001,+0xdb8,+0,+0,+0,+0,+0,+0)).is_ipv6(),+true);%0A%7D&edition=2024 "Run code") 1.75.0 (const: 1.75.0) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#449) #### pub const fn [to\_canonical](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.to_canonical) (&self) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 address, otherwise returns `self` as-is. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-9) Examples use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; let localhost_v4 = Ipv4Addr::new(127, 0, 0, 1); assert_eq!(IpAddr::V4(localhost_v4).to_canonical(), localhost_v4); assert_eq!(IpAddr::V6(localhost_v4.to_ipv6_mapped()).to_canonical(), localhost_v4); assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).to_canonical().is_loopback(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).is_loopback(), false); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).to_canonical().is_loopback(), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++let+localhost_v4+=+Ipv4Addr::new(127,+0,+0,+1);%0A++++%0A++++assert_eq!(IpAddr::V4(localhost_v4).to_canonical(),+localhost_v4);%0A++++assert_eq!(IpAddr::V6(localhost_v4.to_ipv6_mapped()).to_canonical(),+localhost_v4);%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(127,+0,+0,+1)).to_canonical().is_loopback(),+true);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0,+0,+0,+0,+0,+0xffff,+0x7f00,+0x1)).is_loopback(),+false);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::new(0,+0,+0,+0,+0,+0xffff,+0x7f00,+0x1)).to_canonical().is_loopback(),+true);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#471) #### pub const fn [as\_octets](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.as_octets) (&self) -> &\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \] [ⓘ](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#) 🔬This is a nightly-only experimental API. (`ip_as_octets` [#137259](https://github.com/rust-lang/rust/issues/137259) ) Returns the eight-bit integers this address consists of as a slice. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-10) Examples #![feature(ip_as_octets)] use std::net::{Ipv4Addr, Ipv6Addr, IpAddr}; assert_eq!(IpAddr::V4(Ipv4Addr::LOCALHOST).as_octets(), &[127, 0, 0, 1]); assert_eq!(IpAddr::V6(Ipv6Addr::LOCALHOST).as_octets(), &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(ip_as_octets)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::net::%7BIpv4Addr,+Ipv6Addr,+IpAddr%7D;%0A++++%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::LOCALHOST).as_octets(),+%26%5B127,+0,+0,+1%5D);%0A++++assert_eq!(IpAddr::V6(Ipv6Addr::LOCALHOST).as_octets(),%0A+++++++++++++++%26%5B0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1%5D)%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/net/parser.rs.html#295) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-IpAddr-1) ### impl [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/parser.rs.html#310) #### pub fn [parse\_ascii](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.parse_ascii) (b: &\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") , [AddrParseError](https://doc.rust-lang.org/stable/std/net/struct.AddrParseError.html "struct std::net::AddrParseError") \> 🔬This is a nightly-only experimental API. (`addr_parse_ascii` [#101035](https://github.com/rust-lang/rust/issues/101035) ) Parse an IP address from a slice of bytes. #![feature(addr_parse_ascii)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); assert_eq!(IpAddr::parse_ascii(b"127.0.0.1"), Ok(localhost_v4)); assert_eq!(IpAddr::parse_ascii(b"::1"), Ok(localhost_v6)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(addr_parse_ascii)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr,+Ipv6Addr%7D;%0A++++%0A++++let+localhost_v4+=+IpAddr::V4(Ipv4Addr::new(127,+0,+0,+1));%0A++++let+localhost_v6+=+IpAddr::V6(Ipv6Addr::new(0,+0,+0,+0,+0,+0,+0,+1));%0A++++%0A++++assert_eq!(IpAddr::parse_ascii(b%22127.0.0.1%22),+Ok(localhost_v4));%0A++++assert_eq!(IpAddr::parse_ascii(b%22::1%22),+Ok(localhost_v6));%0A%7D&version=nightly&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#trait-implementations) ---------------------------------------------------------------------------------------------------------- 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Clone-for-IpAddr) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1083) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Debug-for-IpAddr) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1084) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, fmt: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1073) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Display-for-IpAddr) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1074) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, fmt: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.17.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2323) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-From%3C%5Bu16;+8%5D%3E-for-IpAddr) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <\[[u16](https://doc.rust-lang.org/stable/std/primitive.u16.html)\ ; [8](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2344) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from-4) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (segments: \[[u16](https://doc.rust-lang.org/stable/std/primitive.u16.html)\ ; [8](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Creates an `IpAddr::V6` from an eight element 16-bit array. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-15) Examples use std::net::{IpAddr, Ipv6Addr}; let addr = IpAddr::from([\ 0x20du16, 0x20cu16, 0x20bu16, 0x20au16,\ 0x209u16, 0x208u16, 0x207u16, 0x206u16,\ ]); assert_eq!( IpAddr::V6(Ipv6Addr::new( 0x20d, 0x20c, 0x20b, 0x20a, 0x209, 0x208, 0x207, 0x206, )), addr ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv6Addr%7D;%0A++++%0A++++let+addr+=+IpAddr::from(%5B%0A++++++++0x20du16,+0x20cu16,+0x20bu16,+0x20au16,%0A++++++++0x209u16,+0x208u16,+0x207u16,+0x206u16,%0A++++%5D);%0A++++assert_eq!(%0A++++++++IpAddr::V6(Ipv6Addr::new(%0A++++++++++++0x20d,+0x20c,+0x20b,+0x20a,%0A++++++++++++0x209,+0x208,+0x207,+0x206,%0A++++++++)),%0A++++++++addr%0A++++);%0A%7D&edition=2024 "Run code") 1.17.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2295) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-From%3C%5Bu8;+16%5D%3E-for-IpAddr) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ ; [16](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2316) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from-3) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (octets: \[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ ; [16](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Creates an `IpAddr::V6` from a sixteen element byte array. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-14) Examples use std::net::{IpAddr, Ipv6Addr}; let addr = IpAddr::from([\ 0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,\ 0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,\ ]); assert_eq!( IpAddr::V6(Ipv6Addr::new( 0x1918, 0x1716, 0x1514, 0x1312, 0x1110, 0x0f0e, 0x0d0c, 0x0b0a, )), addr ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv6Addr%7D;%0A++++%0A++++let+addr+=+IpAddr::from(%5B%0A++++++++0x19u8,+0x18u8,+0x17u8,+0x16u8,+0x15u8,+0x14u8,+0x13u8,+0x12u8,%0A++++++++0x11u8,+0x10u8,+0x0fu8,+0x0eu8,+0x0du8,+0x0cu8,+0x0bu8,+0x0au8,%0A++++%5D);%0A++++assert_eq!(%0A++++++++IpAddr::V6(Ipv6Addr::new(%0A++++++++++++0x1918,+0x1716,+0x1514,+0x1312,%0A++++++++++++0x1110,+0x0f0e,+0x0d0c,+0x0b0a,%0A++++++++)),%0A++++++++addr%0A++++);%0A%7D&edition=2024 "Run code") 1.17.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1264) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-From%3C%5Bu8;+4%5D%3E-for-IpAddr) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ ; [4](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1276) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from-2) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (octets: \[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ ; [4](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Creates an `IpAddr::V4` from a four element byte array. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-13) Examples use std::net::{IpAddr, Ipv4Addr}; let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]); assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr%7D;%0A++++%0A++++let+addr+=+IpAddr::from(%5B13u8,+12u8,+11u8,+10u8%5D);%0A++++assert_eq!(IpAddr::V4(Ipv4Addr::new(13,+12,+11,+10)),+addr);%0A%7D&edition=2024 "Run code") 1.16.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1091) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-From%3CIpv4Addr%3E-for-IpAddr) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1107) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (ipv4: [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") ) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Copies this address to a new `IpAddr::V4`. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-11) Examples use std::net::{IpAddr, Ipv4Addr}; let addr = Ipv4Addr::new(127, 0, 0, 1); assert_eq!( IpAddr::V4(addr), IpAddr::from(addr) ) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv4Addr%7D;%0A++++%0A++++let+addr+=+Ipv4Addr::new(127,+0,+0,+1);%0A++++%0A++++assert_eq!(%0A++++++++IpAddr::V4(addr),%0A++++++++IpAddr::from(addr)%0A++++)%0A%7D&edition=2024 "Run code") 1.16.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143773 "Tracking issue for const_convert") ) · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1114) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-From%3CIpv6Addr%3E-for-IpAddr) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1130) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (ipv6: [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") ) -> [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Copies this address to a new `IpAddr::V6`. ##### [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#examples-12) Examples use std::net::{IpAddr, Ipv6Addr}; let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff); assert_eq!( IpAddr::V6(addr), IpAddr::from(addr) ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::net::%7BIpAddr,+Ipv6Addr%7D;%0A++++%0A++++let+addr+=+Ipv6Addr::new(0,+0,+0,+0,+0,+0xffff,+0xc00a,+0x2ff);%0A++++%0A++++assert_eq!(%0A++++++++IpAddr::V6(addr),%0A++++++++IpAddr::from(addr)%0A++++);%0A%7D&edition=2024 "Run code") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/parser.rs.html#316) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-FromStr-for-IpAddr) ### impl [FromStr](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html "trait std::str::FromStr") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/parser.rs.html#317) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#associatedtype.Err) #### type [Err](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html#associatedtype.Err) = [AddrParseError](https://doc.rust-lang.org/stable/std/net/struct.AddrParseError.html "struct std::net::AddrParseError") The associated error which can be returned from parsing. [Source](https://doc.rust-lang.org/stable/src/core/net/parser.rs.html#318) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from_str) #### fn [from\_str](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html#tymethod.from_str) (s: &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") , [AddrParseError](https://doc.rust-lang.org/stable/std/net/struct.AddrParseError.html "struct std::net::AddrParseError") \> Parses a string `s` to return a value of this type. [Read more](https://doc.rust-lang.org/stable/std/str/trait.FromStr.html#tymethod.from_str) 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Hash-for-IpAddr) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where \_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Ord-for-IpAddr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.cmp) #### fn [cmp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") This method returns an [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") between `self` and `other`. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1021-1023) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.max) #### fn [max](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the maximum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1060-1062) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.min) #### fn [min](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the minimum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1086-1088) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.clamp) #### fn [clamp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (self, min: Self, max: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Restrict a value to a certain interval. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1175) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialEq%3CIpAddr%3E-for-Ipv4Addr) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") \> for [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1177) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.eq-2) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ne-2) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2158) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialEq%3CIpAddr%3E-for-Ipv6Addr) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") \> for [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2160) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.eq-3) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ne-3) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1164) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialEq%3CIpv4Addr%3E-for-IpAddr) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") <[Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1166) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.eq-1) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ne-1) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2169) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialEq%3CIpv6Addr%3E-for-IpAddr) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") <[Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2171) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.eq-4) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ne-4) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialEq-for-IpAddr) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1205) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialOrd%3CIpAddr%3E-for-Ipv4Addr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") \> for [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1207) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.partial_cmp-2) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.lt-2) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.le-2) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.gt-2) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ge-2) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2199) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialOrd%3CIpAddr%3E-for-Ipv6Addr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") \> for [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2201) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.partial_cmp-4) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.lt-4) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.le-4) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.gt-4) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ge-4) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1194) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialOrd%3CIpv4Addr%3E-for-IpAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1196) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.partial_cmp-1) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.lt-1) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.le-1) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.gt-1) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ge-1) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2188) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialOrd%3CIpv6Addr%3E-for-IpAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2190) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.partial_cmp-3) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.lt-3) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.le-3) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.gt-3) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ge-3) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-PartialOrd-for-IpAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.partial_cmp) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.lt) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.le) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.gt) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.ge) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Copy-for-IpAddr) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Eq-for-IpAddr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-StructuralPartialEq-for-IpAddr) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Freeze-for-IpAddr) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-RefUnwindSafe-for-IpAddr) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Send-for-IpAddr) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Sync-for-IpAddr) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Unpin-for-IpAddr) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-UnwindSafe-for-IpAddr) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#blanket-implementations) -------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.from-5) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # BinaryHeap in std::collections - Rust [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) --------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[collections](https://doc.rust-lang.org/stable/std/collections/index.html) Struct BinaryHeap Copy item path ================================ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#274-277) pub struct BinaryHeapwhere A: Allocator,{ /* private fields */ } Expand description A priority queue implemented with a binary heap. This will be a max-heap. It is a logic error for an item to be modified in such a way that the item’s ordering relative to any other item, as determined by the [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") trait, changes while it is in the heap. This is normally only possible through interior mutability, global state, I/O, or unsafe code. The behavior resulting from such a logic error is not specified, but will be encapsulated to the `BinaryHeap` that observed the logic error and not result in undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and non-termination. As long as no elements change their relative order while being in the heap as described above, the API of `BinaryHeap` guarantees that the heap invariant remains intact i.e. its methods all behave as documented. For example if a method is documented as iterating in sorted order, that’s guaranteed to work as long as elements in the heap have not changed order, even in the presence of closures getting unwinded out of, iterators getting leaked, and similar foolishness. [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples) Examples ---------------------------------------------------------------------------------------------- use std::collections::BinaryHeap; // Type inference lets us omit an explicit type signature (which // would be `BinaryHeap` in this example). let mut heap = BinaryHeap::new(); // We can use peek to look at the next item in the heap. In this case, // there's no items in there yet so we get None. assert_eq!(heap.peek(), None); // Let's add some scores... heap.push(1); heap.push(5); heap.push(2); // Now peek shows the most important item in the heap. assert_eq!(heap.peek(), Some(&5)); // We can check the length of a heap. assert_eq!(heap.len(), 3); // We can iterate over the items in the heap, although they are returned in // a random order. for x in &heap { println!("{x}"); } // If we instead pop these scores, they should come back in order. assert_eq!(heap.pop(), Some(5)); assert_eq!(heap.pop(), Some(2)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); // We can clear the heap of any remaining items. heap.clear(); // The heap should now be empty. assert!(heap.is_empty()) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++//+Type+inference+lets+us+omit+an+explicit+type+signature+(which%0A++++//+would+be+%60BinaryHeap%3Ci32%3E%60+in+this+example).%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++%0A++++//+We+can+use+peek+to+look+at+the+next+item+in+the+heap.+In+this+case,%0A++++//+there%27s+no+items+in+there+yet+so+we+get+None.%0A++++assert_eq!(heap.peek(),+None);%0A++++%0A++++//+Let%27s+add+some+scores...%0A++++heap.push(1);%0A++++heap.push(5);%0A++++heap.push(2);%0A++++%0A++++//+Now+peek+shows+the+most+important+item+in+the+heap.%0A++++assert_eq!(heap.peek(),+Some(%265));%0A++++%0A++++//+We+can+check+the+length+of+a+heap.%0A++++assert_eq!(heap.len(),+3);%0A++++%0A++++//+We+can+iterate+over+the+items+in+the+heap,+although+they+are+returned+in%0A++++//+a+random+order.%0A++++for+x+in+%26heap+%7B%0A++++++++println!(%22%7Bx%7D%22);%0A++++%7D%0A++++%0A++++//+If+we+instead+pop+these+scores,+they+should+come+back+in+order.%0A++++assert_eq!(heap.pop(),+Some(5));%0A++++assert_eq!(heap.pop(),+Some(2));%0A++++assert_eq!(heap.pop(),+Some(1));%0A++++assert_eq!(heap.pop(),+None);%0A++++%0A++++//+We+can+clear+the+heap+of+any+remaining+items.%0A++++heap.clear();%0A++++%0A++++//+The+heap+should+now+be+empty.%0A++++assert!(heap.is_empty())%0A%7D&edition=2024 "Run code") A `BinaryHeap` with a known list of items can be initialized from an array: use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 5, 2]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++let+heap+=+BinaryHeap::from(%5B1,+5,+2%5D);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#min-heap) Min-heap Either [`core::cmp::Reverse`](https://doc.rust-lang.org/stable/std/cmp/struct.Reverse.html "struct std::cmp::Reverse") or a custom [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") implementation can be used to make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest value instead of the greatest one. use std::collections::BinaryHeap; use std::cmp::Reverse; let mut heap = BinaryHeap::new(); // Wrap values in `Reverse` heap.push(Reverse(1)); heap.push(Reverse(5)); heap.push(Reverse(2)); // If we pop these scores now, they should come back in the reverse order. assert_eq!(heap.pop(), Some(Reverse(1))); assert_eq!(heap.pop(), Some(Reverse(2))); assert_eq!(heap.pop(), Some(Reverse(5))); assert_eq!(heap.pop(), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++use+std::cmp::Reverse;%0A++++%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++%0A++++//+Wrap+values+in+%60Reverse%60%0A++++heap.push(Reverse(1));%0A++++heap.push(Reverse(5));%0A++++heap.push(Reverse(2));%0A++++%0A++++//+If+we+pop+these+scores+now,+they+should+come+back+in+the+reverse+order.%0A++++assert_eq!(heap.pop(),+Some(Reverse(1)));%0A++++assert_eq!(heap.pop(),+Some(Reverse(2)));%0A++++assert_eq!(heap.pop(),+Some(Reverse(5)));%0A++++assert_eq!(heap.pop(),+None);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#time-complexity) Time complexity ------------------------------------------------------------------------------------------------------------ | [push](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.push "method std::collections::BinaryHeap::push") | [pop](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.pop "method std::collections::BinaryHeap::pop") | [peek](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.peek "method std::collections::BinaryHeap::peek")
/[peek\_mut](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.peek_mut "method std::collections::BinaryHeap::peek_mut") | | --- | --- | --- | | _O_(1)~ | _O_(log(_n_)) | _O_(1) | The value for `push` is an expected cost; the method documentation gives a more detailed analysis. Implementations[§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#implementations) ------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#499) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-BinaryHeap%3CT%3E) ### impl [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.0.0 (const: 1.80.0) · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#514) #### pub const fn [new](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.new) () -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") Creates an empty `BinaryHeap` as a max-heap. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-1) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++heap.push(4);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#535) #### pub fn [with\_capacity](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.with_capacity) (capacity: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") Creates an empty `BinaryHeap` with at least the specified capacity. The binary heap will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is zero, the binary heap will not allocate. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-2) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::with_capacity(10); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::with_capacity(10);%0A++++heap.push(4);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#540) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-BinaryHeap%3CT,+A%3E) ### impl [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#557) #### pub const fn [new\_in](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.new_in) (alloc: A) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Creates an empty `BinaryHeap` as a max-heap, using `A` as allocator. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-3) Examples Basic usage: #![feature(allocator_api)] use std::alloc::System; use std::collections::BinaryHeap; let mut heap = BinaryHeap::new_in(System); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(allocator_api)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::alloc::System;%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new_in(System);%0A++++heap.push(4);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#581) #### pub fn [with\_capacity\_in](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.with_capacity_in) (capacity: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) , alloc: A) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Creates an empty `BinaryHeap` with at least the specified capacity, using `A` as allocator. The binary heap will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is zero, the binary heap will not allocate. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-4) Examples Basic usage: #![feature(allocator_api)] use std::alloc::System; use std::collections::BinaryHeap; let mut heap = BinaryHeap::with_capacity_in(10, System); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(allocator_api)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::alloc::System;%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::with_capacity_in(10,+System);%0A++++heap.push(4);%0A%7D&version=nightly&edition=2024 "Run code") 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#615) #### pub fn [peek\_mut](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.peek_mut) (&mut self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[PeekMut](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.PeekMut.html "struct std::collections::binary_heap::PeekMut") <'\_, T, A>> Returns a mutable reference to the greatest item in the binary heap, or `None` if it is empty. Note: If the `PeekMut` value is leaked, some heap elements might get leaked along with it, but the remaining elements will remain a valid heap. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-5) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); assert!(heap.peek_mut().is_none()); heap.push(1); heap.push(5); heap.push(2); if let Some(mut val) = heap.peek_mut() { *val = 0; } assert_eq!(heap.peek(), Some(&2)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++assert!(heap.peek_mut().is_none());%0A++++%0A++++heap.push(1);%0A++++heap.push(5);%0A++++heap.push(2);%0A++++if+let+Some(mut+val)+=+heap.peek_mut()+%7B%0A++++++++*val+=+0;%0A++++%7D%0A++++assert_eq!(heap.peek(),+Some(%262));%0A%7D&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#time-complexity-1) Time complexity If the item is modified then the worst case time complexity is _O_(log(_n_)), otherwise it’s _O_(1). 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#639) #### pub fn [pop](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.pop) (&mut self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") Removes the greatest item from the binary heap and returns it, or `None` if it is empty. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-6) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 3]); assert_eq!(heap.pop(), Some(3)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::from(%5B1,+3%5D);%0A++++%0A++++assert_eq!(heap.pop(),+Some(3));%0A++++assert_eq!(heap.pop(),+Some(1));%0A++++assert_eq!(heap.pop(),+None);%0A%7D&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#time-complexity-2) Time complexity The worst case cost of `pop` on a heap containing _n_ elements is _O_(log(_n_)). 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#684) #### pub fn [push](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.push) (&mut self, item: T) Pushes an item onto the binary heap. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-7) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.push(3); heap.push(5); heap.push(1); assert_eq!(heap.len(), 3); assert_eq!(heap.peek(), Some(&5)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++heap.push(3);%0A++++heap.push(5);%0A++++heap.push(1);%0A++++%0A++++assert_eq!(heap.len(),+3);%0A++++assert_eq!(heap.peek(),+Some(%265));%0A%7D&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#time-complexity-3) Time complexity The expected cost of `push`, averaged over every possible ordering of the elements being pushed, and over a sufficiently large number of pushes, is _O_(1). This is the most meaningful cost metric when pushing elements that are _not_ already in any sorted pattern. The time complexity degrades if elements are pushed in predominantly ascending order. In the worst case, elements are pushed in ascending sorted order and the amortized cost per push is _O_(log(_n_)) against a heap containing _n_ elements. The worst case cost of a _single_ call to `push` is _O_(_n_). The worst case occurs when capacity is exhausted and needs a resize. The resize cost has been amortized in the previous figures. 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#711) #### pub fn [into\_sorted\_vec](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.into_sorted_vec) (self) -> [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") Consumes the `BinaryHeap` and returns a vector in sorted (ascending) order. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-8) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 2, 4, 5, 7]); heap.push(6); heap.push(3); let vec = heap.into_sorted_vec(); assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++let+mut+heap+=+BinaryHeap::from(%5B1,+2,+4,+5,+7%5D);%0A++++heap.push(6);%0A++++heap.push(3);%0A++++%0A++++let+vec+=+heap.into_sorted_vec();%0A++++assert_eq!(vec,+%5B1,+2,+3,+4,+5,+6,+7%5D);%0A%7D&edition=2024 "Run code") 1.11.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#936) #### pub fn [append](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.append) (&mut self, other: &mut [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") ) Moves all the elements of `other` into `self`, leaving `other` empty. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-9) Examples Basic usage: use std::collections::BinaryHeap; let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]); let mut b = BinaryHeap::from([-20, 5, 43]); a.append(&mut b); assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]); assert!(b.is_empty()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++let+mut+a+=+BinaryHeap::from(%5B-10,+1,+2,+3,+3%5D);%0A++++let+mut+b+=+BinaryHeap::from(%5B-20,+5,+43%5D);%0A++++%0A++++a.append(%26mut+b);%0A++++%0A++++assert_eq!(a.into_sorted_vec(),+%5B-20,+-10,+1,+2,+3,+3,+5,+43%5D);%0A++++assert!(b.is_empty());%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#975) #### pub fn [drain\_sorted](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.drain_sorted) (&mut self) -> [DrainSorted](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.DrainSorted.html "struct std::collections::binary_heap::DrainSorted") <'\_, T, A> [ⓘ](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) 🔬This is a nightly-only experimental API. (`binary_heap_drain_sorted` [#59278](https://github.com/rust-lang/rust/issues/59278) ) Clears the binary heap, returning an iterator over the removed elements in heap order. If the iterator is dropped before being fully consumed, it drops the remaining elements in heap order. The returned iterator keeps a mutable borrow on the heap to optimize its implementation. Note: * `.drain_sorted()` is _O_(_n_ \* log(_n_)); much slower than `.drain()`. You should use the latter for most cases. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-10) Examples Basic usage: #![feature(binary_heap_drain_sorted)] use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]); assert_eq!(heap.len(), 5); drop(heap.drain_sorted()); // removes all elements in heap order assert_eq!(heap.len(), 0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(binary_heap_drain_sorted)%5D%0A%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++let+mut+heap+=+BinaryHeap::from(%5B1,+2,+3,+4,+5%5D);%0A++++assert_eq!(heap.len(),+5);%0A++++%0A++++drop(heap.drain_sorted());+//+removes+all+elements+in+heap+order%0A++++assert_eq!(heap.len(),+0);%0A%7D&version=nightly&edition=2024 "Run code") 1.70.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#998-1000) #### pub fn [retain](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.retain) (&mut self, f: F) where F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") ([&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Retains only the elements specified by the predicate. In other words, remove all elements `e` for which `f(&e)` returns `false`. The elements are visited in unsorted (and unspecified) order. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-11) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]); heap.retain(|x| x % 2 == 0); // only keep even numbers assert_eq!(heap.into_sorted_vec(), [-10, 2, 4]) [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++let+mut+heap+=+BinaryHeap::from(%5B-10,+-5,+1,+2,+4,+13%5D);%0A++++%0A++++heap.retain(%7Cx%7C+x+%25+2+==+0);+//+only+keep+even+numbers%0A++++%0A++++assert_eq!(heap.into_sorted_vec(),+%5B-10,+2,+4%5D)%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1018) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-BinaryHeap%3CT,+A%3E-1) ### impl [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1037) #### pub fn [iter](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.iter) (&self) -> [Iter](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.Iter.html "struct std::collections::binary_heap::Iter") <'\_, T> [ⓘ](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) Returns an iterator visiting all values in the underlying vector, in arbitrary order. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-12) Examples Basic usage: use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4]); // Print 1, 2, 3, 4 in arbitrary order for x in heap.iter() { println!("{x}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+heap+=+BinaryHeap::from(%5B1,+2,+3,+4%5D);%0A++++%0A++++//+Print+1,+2,+3,+4+in+arbitrary+order%0A++++for+x+in+heap.iter()+%7B%0A++++++++println!(%22%7Bx%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1057) #### pub fn [into\_iter\_sorted](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.into_iter_sorted) (self) -> [IntoIterSorted](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.IntoIterSorted.html "struct std::collections::binary_heap::IntoIterSorted") [ⓘ](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) 🔬This is a nightly-only experimental API. (`binary_heap_into_iter_sorted` [#59278](https://github.com/rust-lang/rust/issues/59278) ) Returns an iterator which retrieves elements in heap order. This method consumes the original heap. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-13) Examples Basic usage: #![feature(binary_heap_into_iter_sorted)] use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4, 5]); assert_eq!(heap.into_iter_sorted().take(2).collect::>(), [5, 4]); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(binary_heap_into_iter_sorted)%5D%0A%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+heap+=+BinaryHeap::from(%5B1,+2,+3,+4,+5%5D);%0A++++%0A++++assert_eq!(heap.into_iter_sorted().take(2).collect::%3CVec%3C_%3E%3E(),+%5B5,+4%5D);%0A%7D&version=nightly&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1084) #### pub fn [peek](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.peek) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> Returns the greatest item in the binary heap, or `None` if it is empty. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-14) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); assert_eq!(heap.peek(), None); heap.push(1); heap.push(5); heap.push(2); assert_eq!(heap.peek(), Some(&5)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++assert_eq!(heap.peek(),+None);%0A++++%0A++++heap.push(1);%0A++++heap.push(5);%0A++++heap.push(2);%0A++++assert_eq!(heap.peek(),+Some(%265));%0A%7D&edition=2024 "Run code") ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#time-complexity-4) Time complexity Cost is _O_(1) in the worst case. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1102) #### pub fn [capacity](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.capacity) (&self) -> [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) Returns the number of elements the binary heap can hold without reallocating. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-15) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::with_capacity(100); assert!(heap.capacity() >= 100); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::with_capacity(100);%0A++++assert!(heap.capacity()+%3E=+100);%0A++++heap.push(4);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1133) #### pub fn [reserve\_exact](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.reserve_exact) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) Reserves the minimum capacity for at least `additional` elements more than the current length. Unlike [`reserve`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.reserve "method std::collections::BinaryHeap::reserve") , this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling `reserve_exact`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if the capacity is already sufficient. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#panics) Panics Panics if the new capacity overflows [`usize`](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") . ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-16) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.reserve_exact(100); assert!(heap.capacity() >= 100); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++heap.reserve_exact(100);%0A++++assert!(heap.capacity()+%3E=+100);%0A++++heap.push(4);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1159) #### pub fn [reserve](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.reserve) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) Reserves capacity for at least `additional` elements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if capacity is already sufficient. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#panics-1) Panics Panics if the new capacity overflows [`usize`](https://doc.rust-lang.org/stable/std/primitive.usize.html "primitive usize") . ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-17) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.reserve(100); assert!(heap.capacity() >= 100); heap.push(4); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++heap.reserve(100);%0A++++assert!(heap.capacity()+%3E=+100);%0A++++heap.push(4);%0A%7D&edition=2024 "Run code") 1.63.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1201) #### pub fn [try\_reserve\_exact](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_reserve_exact) ( &mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) , ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [TryReserveError](https://doc.rust-lang.org/stable/std/collections/struct.TryReserveError.html "struct std::collections::TryReserveError") \> Tries to reserve the minimum capacity for at least `additional` elements more than the current length. Unlike [`try_reserve`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_reserve "method std::collections::BinaryHeap::try_reserve") , this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling `try_reserve_exact`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if the capacity is already sufficient. Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer [`try_reserve`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_reserve "method std::collections::BinaryHeap::try_reserve") if future insertions are expected. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#errors) Errors If the capacity overflows, or the allocator reports a failure, then an error is returned. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-18) Examples use std::collections::BinaryHeap; use std::collections::TryReserveError; fn find_max_slow(data: &[u32]) -> Result, TryReserveError> { let mut heap = BinaryHeap::new(); // Pre-reserve the memory, exiting if we can't heap.try_reserve_exact(data.len())?; // Now we know this can't OOM in the middle of our complex work heap.extend(data.iter()); Ok(heap.pop()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++use+std::collections::TryReserveError;%0A++++%0A++++fn+find_max_slow(data:+%26%5Bu32%5D)+-%3E+Result%3COption%3Cu32%3E,+TryReserveError%3E+%7B%0A++++++++let+mut+heap+=+BinaryHeap::new();%0A++++%0A++++++++//+Pre-reserve+the+memory,+exiting+if+we+can%27t%0A++++++++heap.try_reserve_exact(data.len())?;%0A++++%0A++++++++//+Now+we+know+this+can%27t+OOM+in+the+middle+of+our+complex+work%0A++++++++heap.extend(data.iter());%0A++++%0A++++++++Ok(heap.pop())%0A++++%7D%0A++++find_max_slow(%26%5B1,+2,+3%5D).expect(%22why+is+the+test+harness+OOMing+on+12+bytes?%22);%0A%7D&edition=2024 "Run code") 1.63.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1237) #### pub fn [try\_reserve](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_reserve) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [TryReserveError](https://doc.rust-lang.org/stable/std/collections/struct.TryReserveError.html "struct std::collections::TryReserveError") \> Tries to reserve capacity for at least `additional` elements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling `try_reserve`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#errors-1) Errors If the capacity overflows, or the allocator reports a failure, then an error is returned. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-19) Examples use std::collections::BinaryHeap; use std::collections::TryReserveError; fn find_max_slow(data: &[u32]) -> Result, TryReserveError> { let mut heap = BinaryHeap::new(); // Pre-reserve the memory, exiting if we can't heap.try_reserve(data.len())?; // Now we know this can't OOM in the middle of our complex work heap.extend(data.iter()); Ok(heap.pop()) } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++use+std::collections::TryReserveError;%0A++++%0A++++fn+find_max_slow(data:+%26%5Bu32%5D)+-%3E+Result%3COption%3Cu32%3E,+TryReserveError%3E+%7B%0A++++++++let+mut+heap+=+BinaryHeap::new();%0A++++%0A++++++++//+Pre-reserve+the+memory,+exiting+if+we+can%27t%0A++++++++heap.try_reserve(data.len())?;%0A++++%0A++++++++//+Now+we+know+this+can%27t+OOM+in+the+middle+of+our+complex+work%0A++++++++heap.extend(data.iter());%0A++++%0A++++++++Ok(heap.pop())%0A++++%7D%0A++++find_max_slow(%26%5B1,+2,+3%5D).expect(%22why+is+the+test+harness+OOMing+on+12+bytes?%22);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1256) #### pub fn [shrink\_to\_fit](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.shrink_to_fit) (&mut self) Discards as much additional capacity as possible. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-20) Examples Basic usage: use std::collections::BinaryHeap; let mut heap: BinaryHeap = BinaryHeap::with_capacity(100); assert!(heap.capacity() >= 100); heap.shrink_to_fit(); assert!(heap.capacity() == 0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap:+BinaryHeap%3Ci32%3E+=+BinaryHeap::with_capacity(100);%0A++++%0A++++assert!(heap.capacity()+%3E=+100);%0A++++heap.shrink_to_fit();%0A++++assert!(heap.capacity()+==+0);%0A%7D&edition=2024 "Run code") 1.56.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1279) #### pub fn [shrink\_to](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.shrink_to) (&mut self, min\_capacity: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) Discards capacity with a lower bound. The capacity will remain at least as large as both the length and the supplied value. If the current capacity is less than the lower limit, this is a no-op. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-21) Examples use std::collections::BinaryHeap; let mut heap: BinaryHeap = BinaryHeap::with_capacity(100); assert!(heap.capacity() >= 100); heap.shrink_to(10); assert!(heap.capacity() >= 10); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap:+BinaryHeap%3Ci32%3E+=+BinaryHeap::with_capacity(100);%0A++++%0A++++assert!(heap.capacity()+%3E=+100);%0A++++heap.shrink_to(10);%0A++++assert!(heap.capacity()+%3E=+10);%0A%7D&edition=2024 "Run code") 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1300) #### pub fn [as\_slice](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.as_slice) (&self) -> &[\[T\]](https://doc.rust-lang.org/stable/std/primitive.slice.html) Returns a slice of all values in the underlying vector, in arbitrary order. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-22) Examples Basic usage: use std::collections::BinaryHeap; use std::io::{self, Write}; let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]); io::sink().write(heap.as_slice()).unwrap(); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++use+std::io::%7Bself,+Write%7D;%0A++++%0A++++let+heap+=+BinaryHeap::from(%5B1,+2,+3,+4,+5,+6,+7%5D);%0A++++%0A++++io::sink().write(heap.as_slice()).unwrap();%0A%7D&edition=2024 "Run code") 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1323) #### pub fn [into\_vec](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.into_vec) (self) -> [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") Consumes the `BinaryHeap` and returns the underlying vector in arbitrary order. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-23) Examples Basic usage: use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]); let vec = heap.into_vec(); // Will print in some order for x in vec { println!("{x}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+heap+=+BinaryHeap::from(%5B1,+2,+3,+4,+5,+6,+7%5D);%0A++++let+vec+=+heap.into_vec();%0A++++%0A++++//+Will+print+in+some+order%0A++++for+x+in+vec+%7B%0A++++++++println!(%22%7Bx%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1330) #### pub fn [allocator](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.allocator) (&self) -> [&A](https://doc.rust-lang.org/stable/std/primitive.reference.html) 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Returns a reference to the underlying allocator. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1349) #### pub fn [len](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.len) (&self) -> [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) Returns the length of the binary heap. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-24) Examples Basic usage: use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 3]); assert_eq!(heap.len(), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+heap+=+BinaryHeap::from(%5B1,+3%5D);%0A++++%0A++++assert_eq!(heap.len(),+2);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1373) #### pub fn [is\_empty](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.is_empty) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Checks if the binary heap is empty. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-25) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); assert!(heap.is_empty()); heap.push(3); heap.push(5); heap.push(1); assert!(!heap.is_empty()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::new();%0A++++%0A++++assert!(heap.is_empty());%0A++++%0A++++heap.push(3);%0A++++heap.push(5);%0A++++heap.push(1);%0A++++%0A++++assert!(!heap.is_empty());%0A%7D&edition=2024 "Run code") 1.6.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1402) #### pub fn [drain](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.drain) (&mut self) -> [Drain](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.Drain.html "struct std::collections::binary_heap::Drain") <'\_, T, A> [ⓘ](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) Clears the binary heap, returning an iterator over the removed elements in arbitrary order. If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order. The returned iterator keeps a mutable borrow on the heap to optimize its implementation. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-26) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 3]); assert!(!heap.is_empty()); for x in heap.drain() { println!("{x}"); } assert!(heap.is_empty()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::from(%5B1,+3%5D);%0A++++%0A++++assert!(!heap.is_empty());%0A++++%0A++++for+x+in+heap.drain()+%7B%0A++++++++println!(%22%7Bx%7D%22);%0A++++%7D%0A++++%0A++++assert!(heap.is_empty());%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1423) #### pub fn [clear](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.clear) (&mut self) Drops all items from the binary heap. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-27) Examples Basic usage: use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 3]); assert!(!heap.is_empty()); heap.clear(); assert!(heap.is_empty()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+mut+heap+=+BinaryHeap::from(%5B1,+3%5D);%0A++++%0A++++assert!(!heap.is_empty());%0A++++%0A++++heap.clear();%0A++++%0A++++assert!(heap.is_empty());%0A%7D&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#trait-implementations) ------------------------------------------------------------------------------------------------------------------------ 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#452) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Clone-for-BinaryHeap%3CT,+A%3E) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#463) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &[BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") ) Overwrites the contents of `self` with a clone of the contents of `source`. This method is preferred over simply assigning `source.clone()` to `self`, as it avoids reallocation if possible. See [`Vec::clone_from()`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.clone_from "method std::vec::Vec::clone_from") for more details. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#453) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.4.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#478) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Debug-for-BinaryHeap%3CT,+A%3E) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#479) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#469) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Default-for-BinaryHeap%3CT%3E) ### impl [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#472) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.default) #### fn [default](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default) () -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") Creates an empty `BinaryHeap`. 1.2.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1961) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Extend%3C%26T%3E-for-BinaryHeap%3CT,+A%3E) ### impl<'a, T, A> [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") <[&'a T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: 'a + [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1962) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.extend-1) #### fn [extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) (&mut self, iter: I) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Extends a collection with the contents of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1967) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.extend_one-1) #### fn [extend\_one](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_one) (&mut self, \_: [&'a T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Extends a collection with exactly one element. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1972) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.extend_reserve-1) #### fn [extend\_reserve](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Reserves capacity in a collection for the given number of additional elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1942) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Extend%3CT%3E-for-BinaryHeap%3CT,+A%3E) ### impl [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1944) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.extend) #### fn [extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) (&mut self, iter: I) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Extends a collection with the contents of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#tymethod.extend) [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1950) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.extend_one) #### fn [extend\_one](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_one) (&mut self, item: T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Extends a collection with exactly one element. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1955) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.extend_reserve) #### fn [extend\_reserve](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) (&mut self, additional: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631) ) Reserves capacity in a collection for the given number of additional elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html#method.extend_reserve) 1.56.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1870) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-From%3C%5BT;+N%5D%3E-for-BinaryHeap%3CT%3E) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[\[T; N\]](https://doc.rust-lang.org/stable/std/primitive.array.html) \> for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1880) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (arr: [\[T; N\]](https://doc.rust-lang.org/stable/std/primitive.array.html) ) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") use std::collections::BinaryHeap; let mut h1 = BinaryHeap::from([1, 4, 2, 3]); let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into(); while let Some((a, b)) = h1.pop().zip(h2.pop()) { assert_eq!(a, b); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++%0A++++let+mut+h1+=+BinaryHeap::from(%5B1,+4,+2,+3%5D);%0A++++let+mut+h2:+BinaryHeap%3C_%3E+=+%5B1,+4,+2,+3%5D.into();%0A++++while+let+Some((a,+b))+=+h1.pop().zip(h2.pop())+%7B%0A++++++++assert_eq!(a,+b);%0A++++%7D%0A%7D&edition=2024 "Run code") 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1886) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-From%3CBinaryHeap%3CT,+A%3E%3E-for-Vec%3CT,+A%3E) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") > for [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1891) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.from-2) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (heap: [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") ) -> [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") Converts a `BinaryHeap` into a `Vec`. This conversion requires no data movement or allocation, and has constant time complexity. 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1858) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-From%3CVec%3CT,+A%3E%3E-for-BinaryHeap%3CT,+A%3E) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") > for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1862) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (vec: [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") ) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") Converts a `Vec` into a `BinaryHeap`. This conversion happens in-place, and has _O_(_n_) time complexity. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-FromIterator%3CT%3E-for-BinaryHeap%3CT%3E) ### impl [FromIterator](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html "trait std::iter::FromIterator") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1898) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.from_iter) #### fn [from\_iter](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) (iter: I) -> [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Creates a value from an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html#tymethod.from_iter) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1932) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-IntoIterator-for-%26BinaryHeap%3CT,+A%3E) ### impl<'a, T, A> [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") for &'a [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1933) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.Item-1) #### type [Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item) = [&'a T](https://doc.rust-lang.org/stable/std/primitive.reference.html) The type of the elements being iterated over. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1934) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.IntoIter-1) #### type [IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter) = [Iter](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.Iter.html "struct std::collections::binary_heap::Iter") <'a, T> Which kind of iterator are we turning this into? [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1936) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.into_iter-1) #### fn [into\_iter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) (self) -> [Iter](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.Iter.html "struct std::collections::binary_heap::Iter") <'a, T> [ⓘ](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) Creates an iterator from a value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1904) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-IntoIterator-for-BinaryHeap%3CT,+A%3E) ### impl [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1926) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.into_iter) #### fn [into\_iter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) (self) -> [IntoIter](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.IntoIter.html "struct std::collections::binary_heap::IntoIter") [ⓘ](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#) Creates a consuming iterator, that is, one that moves each value out of the binary heap in arbitrary order. The binary heap cannot be used after calling this. ##### [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#examples-28) Examples Basic usage: use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4]); // Print 1, 2, 3, 4 in arbitrary order for x in heap.into_iter() { // x has type i32, not &i32 println!("{x}"); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::collections::BinaryHeap;%0A++++let+heap+=+BinaryHeap::from(%5B1,+2,+3,+4%5D);%0A++++%0A++++//+Print+1,+2,+3,+4+in+arbitrary+order%0A++++for+x+in+heap.into_iter()+%7B%0A++++++++//+x+has+type+i32,+not+%26i32%0A++++++++println!(%22%7Bx%7D%22);%0A++++%7D%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1905) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.Item) #### type [Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item) = T The type of the elements being iterated over. [Source](https://doc.rust-lang.org/stable/src/alloc/collections/binary_heap/mod.rs.html#1906) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.IntoIter) #### type [IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter) = [IntoIter](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.IntoIter.html "struct std::collections::binary_heap::IntoIter") Which kind of iterator are we turning this into? Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#synthetic-implementations) --------------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Freeze-for-BinaryHeap%3CT,+A%3E) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") , [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-RefUnwindSafe-for-BinaryHeap%3CT,+A%3E) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") , T: [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") , [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Send-for-BinaryHeap%3CT,+A%3E) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") , T: [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") , [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Sync-for-BinaryHeap%3CT,+A%3E) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") , T: [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") , [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Unpin-for-BinaryHeap%3CT,+A%3E) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , T: [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-UnwindSafe-for-BinaryHeap%3CT,+A%3E) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [BinaryHeap](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html "struct std::collections::BinaryHeap") where A: [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") , T: [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") , Blanket Implementations[§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#blanket-implementations) ---------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.from-3) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Ord in std::cmp - Rust [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#) ---------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[cmp](https://doc.rust-lang.org/stable/std/cmp/index.html) Trait Ord Copy item path ======================== 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#969) pub trait Ord: Eq + PartialOrd { // Required method fn cmp(&self, other: &Self) -> Ordering; // Provided methods fn max(self, other: Self) -> Self where Self: Sized { ... } fn min(self, other: Self) -> Self where Self: Sized { ... } fn clamp(self, min: Self, max: Self) -> Self where Self: Sized { ... } } Expand description Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order) . Implementations must be consistent with the [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") implementation, and ensure `max`, `min`, and `clamp` are consistent with `cmp`: * `partial_cmp(a, b) == Some(cmp(a, b))`. * `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation). * `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation). * For `a.clamp(min, max)`, see the [method docs](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (ensured by the default implementation). Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do _not_ result in undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these methods. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#corollaries) Corollaries From the above and the requirements of `PartialOrd`, it follows that for all `a`, `b` and `c`: * exactly one of `a < b`, `a == b` or `a > b` is true; and * `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. Mathematically speaking, the `<` operator defines a strict [weak order](https://en.wikipedia.org/wiki/Weak_ordering) . In cases where `==` conforms to mathematical equality, it also defines a strict [total order](https://en.wikipedia.org/wiki/Total_order) . ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#derivable) Derivable This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct’s members. When `derive`d on enums, variants are ordered primarily by their discriminants. Secondarily, they are ordered by their fields. By default, the discriminant is smallest for variants at the top, and largest for variants at the bottom. Here’s an example: #[derive(PartialEq, Eq, PartialOrd, Ord)] enum E { Top, Bottom, } assert!(E::Top < E::Bottom); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(PartialEq,+Eq,+PartialOrd,+Ord)%5D%0A++++enum+E+%7B%0A++++++++Top,%0A++++++++Bottom,%0A++++%7D%0A++++%0A++++assert!(E::Top+%3C+E::Bottom);%0A%7D&edition=2024 "Run code") However, manually setting the discriminants can override this default behavior: #[derive(PartialEq, Eq, PartialOrd, Ord)] enum E { Top = 2, Bottom = 1, } assert!(E::Bottom < E::Top); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(PartialEq,+Eq,+PartialOrd,+Ord)%5D%0A++++enum+E+%7B%0A++++++++Top+=+2,%0A++++++++Bottom+=+1,%0A++++%7D%0A++++%0A++++assert!(E::Bottom+%3C+E::Top);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison) Lexicographical comparison Lexicographical comparison is an operation with the following properties: * Two sequences are compared element by element. * The first mismatching element defines which sequence is lexicographically less or greater than the other. * If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other. * If two sequences have equivalent elements and are of the same length, then the sequences are lexicographically equal. * An empty sequence is lexicographically less than any non-empty sequence. * Two empty sequences are lexicographically equal. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#how-can-i-implement-ord) How can I implement `Ord`? `Ord` requires that the type also be [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") , and [`Eq`](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") . Because `Ord` implies a stronger ordering relationship than [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , and both `Ord` and [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") must agree, you must choose how to implement `Ord` **first**. You can choose to derive it, or implement it manually. If you derive it, you should derive all four traits. If you implement it manually, you should manually implement all four traits, based on the implementation of `Ord`. Here’s an example where you want to define the `Character` comparison by `health` and `experience` only, disregarding the field `mana`: use std::cmp::Ordering; struct Character { health: u32, experience: u32, mana: f32, } impl Ord for Character { fn cmp(&self, other: &Self) -> Ordering { self.experience .cmp(&other.experience) .then(self.health.cmp(&other.health)) } } impl PartialOrd for Character { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Character { fn eq(&self, other: &Self) -> bool { self.health == other.health && self.experience == other.experience } } impl Eq for Character {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++struct+Character+%7B%0A++++++++health:+u32,%0A++++++++experience:+u32,%0A++++++++mana:+f32,%0A++++%7D%0A++++%0A++++impl+Ord+for+Character+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+Ordering+%7B%0A++++++++++++self.experience%0A++++++++++++++++.cmp(%26other.experience)%0A++++++++++++++++.then(self.health.cmp(%26other.health))%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Character+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B%0A++++++++++++Some(self.cmp(other))%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+PartialEq+for+Character+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B%0A++++++++++++self.health+==+other.health+%26%26+self.experience+==+other.experience%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Eq+for+Character+%7B%7D%0A%7D&edition=2024 "Run code") If all you need is to `slice::sort` a type by a field value, it can be simpler to use `slice::sort_by_key`. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#examples-of-incorrect-ord-implementations) Examples of incorrect `Ord` implementations use std::cmp::Ordering; #[derive(Debug)] struct Character { health: f32, } impl Ord for Character { fn cmp(&self, other: &Self) -> std::cmp::Ordering { if self.health < other.health { Ordering::Less } else if self.health > other.health { Ordering::Greater } else { Ordering::Equal } } } impl PartialOrd for Character { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Character { fn eq(&self, other: &Self) -> bool { self.health == other.health } } impl Eq for Character {} let a = Character { health: 4.5 }; let b = Character { health: f32::NAN }; // Mistake: floating-point values do not form a total order and using the built-in comparison // operands to implement `Ord` irregardless of that reality does not change it. Use // `f32::total_cmp` if you need a total order for floating-point values. // Reflexivity requirement of `Ord` is not given. assert!(a == a); assert!(b != b); // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be // true, not both or neither. assert_eq!((a < b) as u8 + (b < a) as u8, 0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++%23%5Bderive(Debug)%5D%0A++++struct+Character+%7B%0A++++++++health:+f32,%0A++++%7D%0A++++%0A++++impl+Ord+for+Character+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+std::cmp::Ordering+%7B%0A++++++++++++if+self.health+%3C+other.health+%7B%0A++++++++++++++++Ordering::Less%0A++++++++++++%7D+else+if+self.health+%3E+other.health+%7B%0A++++++++++++++++Ordering::Greater%0A++++++++++++%7D+else+%7B%0A++++++++++++++++Ordering::Equal%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Character+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B%0A++++++++++++Some(self.cmp(other))%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+PartialEq+for+Character+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B%0A++++++++++++self.health+==+other.health%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Eq+for+Character+%7B%7D%0A++++%0A++++let+a+=+Character+%7B+health:+4.5+%7D;%0A++++let+b+=+Character+%7B+health:+f32::NAN+%7D;%0A++++%0A++++//+Mistake:+floating-point+values+do+not+form+a+total+order+and+using+the+built-in+comparison%0A++++//+operands+to+implement+%60Ord%60+irregardless+of+that+reality+does+not+change+it.+Use%0A++++//+%60f32::total_cmp%60+if+you+need+a+total+order+for+floating-point+values.%0A++++%0A++++//+Reflexivity+requirement+of+%60Ord%60+is+not+given.%0A++++assert!(a+==+a);%0A++++assert!(b+!=+b);%0A++++%0A++++//+Antisymmetry+requirement+of+%60Ord%60+is+not+given.+Only+one+of+a+%3C+c+and+c+%3C+a+is+allowed+to+be%0A++++//+true,+not+both+or+neither.%0A++++assert_eq!((a+%3C+b)+as+u8+%2B+(b+%3C+a)+as+u8,+0);%0A%7D&edition=2024 "Run code") use std::cmp::Ordering; #[derive(Debug)] struct Character { health: u32, experience: u32, } impl PartialOrd for Character { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Character { fn cmp(&self, other: &Self) -> std::cmp::Ordering { if self.health < 50 { self.health.cmp(&other.health) } else { self.experience.cmp(&other.experience) } } } // For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it // ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example. impl PartialEq for Character { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for Character {} let a = Character { health: 3, experience: 5, }; let b = Character { health: 10, experience: 77, }; let c = Character { health: 143, experience: 2, }; // Mistake: The implementation of `Ord` compares different fields depending on the value of // `self.health`, the resulting order is not total. // Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than // c, by transitive property a must also be smaller than c. assert!(a < b && b < c && c < a); // Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be // true, not both or neither. assert_eq!((a < c) as u8 + (c < a) as u8, 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++%23%5Bderive(Debug)%5D%0A++++struct+Character+%7B%0A++++++++health:+u32,%0A++++++++experience:+u32,%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Character+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B%0A++++++++++++Some(self.cmp(other))%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Ord+for+Character+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+std::cmp::Ordering+%7B%0A++++++++++++if+self.health+%3C+50+%7B%0A++++++++++++++++self.health.cmp(%26other.health)%0A++++++++++++%7D+else+%7B%0A++++++++++++++++self.experience.cmp(%26other.experience)%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+For+performance+reasons+implementing+%60PartialEq%60+this+way+is+not+the+idiomatic+way,+but+it%0A++++//+ensures+consistent+behavior+between+%60PartialEq%60,+%60PartialOrd%60+and+%60Ord%60+in+this+example.%0A++++impl+PartialEq+for+Character+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B%0A++++++++++++self.cmp(other)+==+Ordering::Equal%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Eq+for+Character+%7B%7D%0A++++%0A++++let+a+=+Character+%7B%0A++++++++health:+3,%0A++++++++experience:+5,%0A++++%7D;%0A++++let+b+=+Character+%7B%0A++++++++health:+10,%0A++++++++experience:+77,%0A++++%7D;%0A++++let+c+=+Character+%7B%0A++++++++health:+143,%0A++++++++experience:+2,%0A++++%7D;%0A++++%0A++++//+Mistake:+The+implementation+of+%60Ord%60+compares+different+fields+depending+on+the+value+of%0A++++//+%60self.health%60,+the+resulting+order+is+not+total.%0A++++%0A++++//+Transitivity+requirement+of+%60Ord%60+is+not+given.+If+a+is+smaller+than+b+and+b+is+smaller+than%0A++++//+c,+by+transitive+property+a+must+also+be+smaller+than+c.%0A++++assert!(a+%3C+b+%26%26+b+%3C+c+%26%26+c+%3C+a);%0A++++%0A++++//+Antisymmetry+requirement+of+%60Ord%60+is+not+given.+Only+one+of+a+%3C+c+and+c+%3C+a+is+allowed+to+be%0A++++//+true,+not+both+or+neither.%0A++++assert_eq!((a+%3C+c)+as+u8+%2B+(c+%3C+a)+as+u8,+2);%0A%7D&edition=2024 "Run code") The documentation of [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") contains further examples, for example it’s wrong for [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") and [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") to disagree. Required Methods[§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#required-methods) ---------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#987) #### fn [cmp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) (&self, other: &Self) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") This method returns an [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") between `self` and `other`. By convention, `self.cmp(&other)` returns the ordering matching the expression `self other` if true. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#examples) Examples use std::cmp::Ordering; assert_eq!(5.cmp(&10), Ordering::Less); assert_eq!(10.cmp(&5), Ordering::Greater); assert_eq!(5.cmp(&5), Ordering::Equal); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++assert_eq!(5.cmp(%2610),+Ordering::Less);%0A++++assert_eq!(10.cmp(%265),+Ordering::Greater);%0A++++assert_eq!(5.cmp(%265),+Ordering::Equal);%0A%7D&edition=2024 "Run code") Provided Methods[§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#provided-methods) ---------------------------------------------------------------------------------------------- 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1021-1023) #### fn [max](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the maximum of two values. Returns the second argument if the comparison determines them to be equal. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#examples-1) Examples assert_eq!(1.max(2), 2); assert_eq!(2.max(2), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1.max(2),+2);%0A++++assert_eq!(2.max(2),+2);%0A%7D&edition=2024 "Run code") use std::cmp::Ordering; #[derive(Eq)] struct Equal(&'static str); impl PartialEq for Equal { fn eq(&self, other: &Self) -> bool { true } } impl PartialOrd for Equal { fn partial_cmp(&self, other: &Self) -> Option { Some(Ordering::Equal) } } impl Ord for Equal { fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal } } assert_eq!(Equal("self").max(Equal("other")).0, "other"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++%23%5Bderive(Eq)%5D%0A++++struct+Equal(%26%27static+str);%0A++++%0A++++impl+PartialEq+for+Equal+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B+true+%7D%0A++++%7D%0A++++impl+PartialOrd+for+Equal+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B+Some(Ordering::Equal)+%7D%0A++++%7D%0A++++impl+Ord+for+Equal+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+Ordering+%7B+Ordering::Equal+%7D%0A++++%7D%0A++++%0A++++assert_eq!(Equal(%22self%22).max(Equal(%22other%22)).0,+%22other%22);%0A%7D&edition=2024 "Run code") 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1060-1062) #### fn [min](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the minimum of two values. Returns the first argument if the comparison determines them to be equal. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#examples-2) Examples assert_eq!(1.min(2), 1); assert_eq!(2.min(2), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1.min(2),+1);%0A++++assert_eq!(2.min(2),+2);%0A%7D&edition=2024 "Run code") use std::cmp::Ordering; #[derive(Eq)] struct Equal(&'static str); impl PartialEq for Equal { fn eq(&self, other: &Self) -> bool { true } } impl PartialOrd for Equal { fn partial_cmp(&self, other: &Self) -> Option { Some(Ordering::Equal) } } impl Ord for Equal { fn cmp(&self, other: &Self) -> Ordering { Ordering::Equal } } assert_eq!(Equal("self").min(Equal("other")).0, "self"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++%23%5Bderive(Eq)%5D%0A++++struct+Equal(%26%27static+str);%0A++++%0A++++impl+PartialEq+for+Equal+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B+true+%7D%0A++++%7D%0A++++impl+PartialOrd+for+Equal+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B+Some(Ordering::Equal)+%7D%0A++++%7D%0A++++impl+Ord+for+Equal+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+Ordering+%7B+Ordering::Equal+%7D%0A++++%7D%0A++++%0A++++assert_eq!(Equal(%22self%22).min(Equal(%22other%22)).0,+%22self%22);%0A%7D&edition=2024 "Run code") 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1086-1088) #### fn [clamp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (self, min: Self, max: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Restrict a value to a certain interval. Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`. Otherwise this returns `self`. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#panics) Panics Panics if `min > max`. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#examples-3) Examples assert_eq!((-3).clamp(-2, 1), -2); assert_eq!(0.clamp(-2, 1), 0); assert_eq!(2.clamp(-2, 1), 1); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!((-3).clamp(-2,+1),+-2);%0A++++assert_eq!(0.clamp(-2,+1),+0);%0A++++assert_eq!(2.clamp(-2,+1),+1);%0A%7D&edition=2024 "Run code") Dyn Compatibility[§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#dyn-compatibility) ------------------------------------------------------------------------------------------------ This trait is **not** [dyn compatible](https://doc.rust-lang.org/1.92.0/reference/items/traits.html#dyn-compatibility) . _In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe._ Implementors[§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#implementors) -------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Char) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#979) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Infallible) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-ErrorKind) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-IpAddr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#31) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-SocketAddr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [SocketAddr](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html "enum std::net::SocketAddr") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#385) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Ordering) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2015) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-bool) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-char) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [char](https://doc.rust-lang.org/stable/std/primitive.char.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-i8) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [i8](https://doc.rust-lang.org/stable/std/primitive.i8.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-i16) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [i16](https://doc.rust-lang.org/stable/std/primitive.i16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-i32) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [i32](https://doc.rust-lang.org/stable/std/primitive.i32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-i64) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [i64](https://doc.rust-lang.org/stable/std/primitive.i64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-i128) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [i128](https://doc.rust-lang.org/stable/std/primitive.i128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-isize) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [isize](https://doc.rust-lang.org/stable/std/primitive.isize.html) [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2073) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-!) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [!](https://doc.rust-lang.org/stable/std/primitive.never.html) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/traits.rs.html#18) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-str) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [str](https://doc.rust-lang.org/stable/std/primitive.str.html) Implements ordering of strings. Strings are ordered [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") by their byte values. This orders Unicode code points based on their positions in the code charts. This is not necessarily the same as “alphabetical” order, which varies by language and locale. Sorting strings according to culturally-accepted standards requires locale-specific data that is outside the scope of the `str` type. 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-u8) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-u16) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-u32) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-u64) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-u128) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2006) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-()) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [()](https://doc.rust-lang.org/stable/std/primitive.unit.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-usize) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/stdarch/crates/core_arch/src/x86/cpuid.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-CpuidResult) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [CpuidResult](https://doc.rust-lang.org/stable/core/core_arch/x86/cpuid/struct.CpuidResult.html "struct core::core_arch::x86::cpuid::CpuidResult") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-TypeId) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/bstr/traits.rs.html#9) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-ByteStr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#545) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-ByteString) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#678) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-CStr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [CStr](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/ffi/c_str.rs.html#104) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-CString) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [CString](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1548-1553) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-OsStr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#796-801) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-OsString) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#106) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Error) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") 1.33.0 · [Source](https://doc.rust-lang.org/stable/src/core/marker.rs.html#1024) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomPinned) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomPinned](https://doc.rust-lang.org/stable/std/marker/struct.PhantomPinned.html "struct std::marker::PhantomPinned") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1216) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Ipv4Addr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2210) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Ipv6Addr) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#79) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-SocketAddrV4) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [SocketAddrV4](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html "struct std::net::SocketAddrV4") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#145) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-SocketAddrV6) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [SocketAddrV6](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html "struct std::net::SocketAddrV6") 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/panic/location.rs.html#62) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Location%3C'_%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Location](https://doc.rust-lang.org/stable/std/panic/struct.Location.html "struct std::panic::Location") <'\_> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#1027-1032) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Components%3C'_%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Components](https://doc.rust-lang.org/stable/std/path/struct.Components.html "struct std::path::Components") <'\_> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3690-3695) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Path) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#2250-2255) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PathBuf) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#464-469) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PrefixComponent%3C'_%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PrefixComponent](https://doc.rust-lang.org/stable/std/path/struct.PrefixComponent.html "struct std::path::PrefixComponent") <'\_> [Source](https://doc.rust-lang.org/stable/src/core/ptr/alignment.rs.html#214) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Alignment) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Alignment](https://doc.rust-lang.org/stable/std/ptr/struct.Alignment.html "struct std::ptr::Alignment") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#357) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-String) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Duration) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#155) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Instant) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#249) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-SystemTime) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#500) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Component%3C'a%3E) ### impl<'a> [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Component](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") <'a> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#135) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Prefix%3C'a%3E) ### impl<'a> [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Prefix](https://doc.rust-lang.org/stable/std/path/enum.Prefix.html "enum std::path::Prefix") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomContravariantLifetime%3C'a%3E) ### impl<'a> [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomContravariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariantLifetime.html "struct std::marker::PhantomContravariantLifetime") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomCovariantLifetime%3C'a%3E) ### impl<'a> [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomCovariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariantLifetime.html "struct std::marker::PhantomCovariantLifetime") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomInvariantLifetime%3C'a%3E) ### impl<'a> [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomInvariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariantLifetime.html "struct std::marker::PhantomInvariantLifetime") <'a> 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2142-2144) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-%26A) ### impl
[Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [&A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2217-2219) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-%26mut+A) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [&mut A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#366-368) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Cow%3C'_,+B%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, B> where B: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/ptr/metadata.rs.html#243) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-DynMetadata%3CDyn%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [DynMetadata](https://doc.rust-lang.org/stable/std/ptr/struct.DynMetadata.html "struct std::ptr::DynMetadata") where Dyn: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.4.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mod.rs.html#2576) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-F) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for F where F: [FnPtr](https://doc.rust-lang.org/stable/std/marker/trait.FnPtr.html "trait std::marker::FnPtr") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/map.rs.html#2433) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-BTreeMap%3CK,+V,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [BTreeMap](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") where K: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , V: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 1.41.0 · [Source](https://doc.rust-lang.org/stable/src/core/pin.rs.html#1148) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Pin%3CPtr%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") where Ptr: [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") , ::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "type std::ops::Deref::Target") : [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/option.rs.html#2387) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Option%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/task/poll.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Poll%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Poll](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/const_ptr.rs.html#1583) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-*const+T) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [\*const T](https://doc.rust-lang.org/stable/std/primitive.pointer.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Pointer comparison is by address, as produced by the `[`<\*const T>::addr`](pointer::addr)` method. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mut_ptr.rs.html#2016) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-*mut+T) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [\*mut T](https://doc.rust-lang.org/stable/std/primitive.pointer.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Pointer comparison is by address, as produced by the [`<*mut T>::addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.addr "method pointer::addr") method. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/cmp.rs.html#31) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-%5BT%5D) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [\[T\]](https://doc.rust-lang.org/stable/std/primitive.slice.html) where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Implements comparison of slices [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") . 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/tuple.rs.html#238) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-(T,)) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [(T₁, T₂, …, Tₙ)](https://doc.rust-lang.org/stable/std/primitive.tuple.html#trait-implementations-1) where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , This trait is implemented for tuples up to twelve items long. 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#386) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Cell%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Cell](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#1496) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-RefCell%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [RefCell](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomContravariant%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomContravariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariant.html "struct std::marker::PhantomContravariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomCovariant%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomCovariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariant.html "struct std::marker::PhantomCovariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/marker.rs.html#848) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomData%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomData](https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html "struct std::marker::PhantomData") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-PhantomInvariant%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [PhantomInvariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariant.html "struct std::marker::PhantomInvariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.20.0 · [Source](https://doc.rust-lang.org/stable/src/core/mem/manually_drop.rs.html#155) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-ManuallyDrop%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [ManuallyDrop](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "struct std::mem::ManuallyDrop") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/num/nonzero.rs.html#260-264) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-NonZero%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [NonZero](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html "struct std::num::NonZero") where T: [ZeroablePrimitive](https://doc.rust-lang.org/stable/std/num/trait.ZeroablePrimitive.html "trait std::num::ZeroablePrimitive") + [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.74.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/saturating.rs.html#35) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Saturating%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Saturating](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html "struct std::num::Saturating") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/wrapping.rs.html#40) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Wrapping%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Wrapping](https://doc.rust-lang.org/stable/std/num/struct.Wrapping.html "struct std::num::Wrapping") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.25.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/non_null.rs.html#1692) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-NonNull%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/sync/exclusive.rs.html#309-311) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Exclusive%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Exclusive](https://doc.rust-lang.org/stable/std/sync/struct.Exclusive.html "struct std::sync::Exclusive") where T: [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") + [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.19.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#701) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Reverse%3CT%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Reverse](https://doc.rust-lang.org/stable/std/cmp/struct.Reverse.html "struct std::cmp::Reverse") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed.rs.html#1885) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Box%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/set.rs.html#110) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-BTreeSet%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [BTreeSet](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html "struct std::collections::BTreeSet") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/linked_list.rs.html#2143) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-LinkedList%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [LinkedList](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/vec_deque/mod.rs.html#3044) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-VecDeque%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [VecDeque](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#2589) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Rc%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Rc](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#3949) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-UniqueRc%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [UniqueRc](https://doc.rust-lang.org/stable/std/rc/struct.UniqueRc.html "struct std::rc::UniqueRc") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#3492) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Arc%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Arc](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#4361) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-UniqueArc%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [UniqueArc](https://doc.rust-lang.org/stable/std/sync/struct.UniqueArc.html "struct std::sync::UniqueArc") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/vec/mod.rs.html#4033) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Vec%3CT,+A%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , Implements ordering of vectors, [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") . 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/result.rs.html#553) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Result%3CT,+E%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , E: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/array/mod.rs.html#431) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-%5BT;+N%5D) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [\[T; N\]](https://doc.rust-lang.org/stable/std/primitive.array.html) where T: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Implements comparison of arrays [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") . [Source](https://doc.rust-lang.org/stable/src/core/portable-simd/crates/core_simd/src/vector.rs.html#972-975) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-Simd%3CT,+N%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Simd](https://doc.rust-lang.org/stable/std/simd/struct.Simd.html "struct std::simd::Simd") where [LaneCount](https://doc.rust-lang.org/stable/std/simd/struct.LaneCount.html "struct std::simd::LaneCount") : [SupportedLaneCount](https://doc.rust-lang.org/stable/std/simd/trait.SupportedLaneCount.html "trait std::simd::SupportedLaneCount") , T: [SimdElement](https://doc.rust-lang.org/stable/std/simd/trait.SimdElement.html "trait std::simd::SimdElement") + [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Lexicographic order. For the SIMD elementwise minimum and maximum, use simd\_min and simd\_max instead. [Source](https://doc.rust-lang.org/stable/src/core/ops/coroutine.rs.html#8) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#impl-Ord-for-CoroutineState%3CY,+R%3E) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [CoroutineState](https://doc.rust-lang.org/stable/std/ops/enum.CoroutineState.html "enum std::ops::CoroutineState") where Y: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , R: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , --- # PartialOrd in std::cmp - Rust [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#) ------------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) ::[cmp](https://doc.rust-lang.org/stable/std/cmp/index.html) Trait PartialOrd Copy item path =============================== 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1354-1355) pub trait PartialOrd: PartialEqwhere Rhs: ?Sized,{ // Required method fn partial_cmp(&self, other: &Rhs) -> Option; // Provided methods fn lt(&self, other: &Rhs) -> bool { ... } fn le(&self, other: &Rhs) -> bool { ... } fn gt(&self, other: &Rhs) -> bool { ... } fn ge(&self, other: &Rhs) -> bool { ... } } Expand description Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order) . The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using the `<`, `<=`, `>`, and `>=` operators, respectively. This trait should **only** contain the comparison logic for a type **if one plans on only implementing `PartialOrd` but not [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") **. Otherwise the comparison logic should be in [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") and this trait implemented with `Some(self.cmp(other))`. The methods of this trait must be consistent with each other and with those of [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") . The following conditions must hold: 1. `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`. 2. `a < b` if and only if `partial_cmp(a, b) == Some(Less)` 3. `a > b` if and only if `partial_cmp(a, b) == Some(Greater)` 4. `a <= b` if and only if `a < b || a == b` 5. `a >= b` if and only if `a > b || a == b` 6. `a != b` if and only if `!(a == b)`. Conditions 2–5 above are ensured by the default implementation. Condition 6 is already ensured by [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") . If [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") is also implemented for `Self` and `Rhs`, it must also be consistent with `partial_cmp` (see the documentation of that trait for the exact requirements). It’s easy to accidentally make them disagree by deriving some of the traits and manually implementing others. The comparison relations must satisfy the following conditions (for all `a`, `b`, `c` of type `A`, `B`, `C`): * **Transitivity**: if `A: PartialOrd` and `B: PartialOrd` and `A: PartialOrd`, then `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. This must also work for longer chains, such as when `A: PartialOrd`, `B: PartialOrd`, `C: PartialOrd`, and `A: PartialOrd` all exist. * **Duality**: if `A: PartialOrd` and `B: PartialOrd`, then `a < b` if and only if `b > a`. Note that the `B: PartialOrd` (dual) and `A: PartialOrd` (transitive) impls are not forced to exist, but these requirements apply whenever they do exist. Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do _not_ result in undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these methods. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#cross-crate-considerations) Cross-crate considerations Upholding the requirements stated above can become tricky when one crate implements `PartialOrd` for a type of another crate (i.e., to allow comparing one of its own types with a type from the standard library). The recommendation is to never implement this trait for a foreign type. In other words, such a crate should do `impl PartialOrd for LocalType`, but it should _not_ do `impl PartialOrd for ForeignType`. This avoids the problem of transitive chains that criss-cross crate boundaries: for all local types `T`, you may assume that no other crate will add `impl`s that allow comparing `T < U`. In other words, if other crates add `impl`s that allow building longer transitive chains `U1 < ... < T < V1 < ...`, then all the types that appear to the right of `T` must be types that the crate defining `T` already knows about. This rules out transitive chains where downstream crates can add new `impl`s that “stitch together” comparisons of foreign types in ways that violate transitivity. Not having such foreign `impl`s also avoids forward compatibility issues where one crate adding more `PartialOrd` implementations can cause build failures in downstream crates. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#corollaries) Corollaries The following corollaries follow from the above requirements: * irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)` * transitivity of `>`: if `a > b` and `b > c` then `a > c` * duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)` ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#strict-and-non-strict-partial-orders) Strict and non-strict partial orders The `<` and `>` operators behave according to a _strict_ partial order. However, `<=` and `>=` do **not** behave according to a _non-strict_ partial order. That is because mathematically, a non-strict partial order would require reflexivity, i.e. `a <= a` would need to be true for every `a`. This isn’t always the case for types that implement `PartialOrd`, for example: let a = f64::sqrt(-1.0); assert_eq!(a <= a, false); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+a+=+f64::sqrt(-1.0);%0A++++assert_eq!(a+%3C=+a,+false);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#derivable) Derivable This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct’s members. When `derive`d on enums, variants are primarily ordered by their discriminants. Secondarily, they are ordered by their fields. By default, the discriminant is smallest for variants at the top, and largest for variants at the bottom. Here’s an example: #[derive(PartialEq, PartialOrd)] enum E { Top, Bottom, } assert!(E::Top < E::Bottom); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(PartialEq,+PartialOrd)%5D%0A++++enum+E+%7B%0A++++++++Top,%0A++++++++Bottom,%0A++++%7D%0A++++%0A++++assert!(E::Top+%3C+E::Bottom);%0A%7D&edition=2024 "Run code") However, manually setting the discriminants can override this default behavior: #[derive(PartialEq, PartialOrd)] enum E { Top = 2, Bottom = 1, } assert!(E::Bottom < E::Top); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++%23%5Bderive(PartialEq,+PartialOrd)%5D%0A++++enum+E+%7B%0A++++++++Top+=+2,%0A++++++++Bottom+=+1,%0A++++%7D%0A++++%0A++++assert!(E::Bottom+%3C+E::Top);%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#how-can-i-implement-partialord) How can I implement `PartialOrd`? `PartialOrd` only requires implementation of the [`partial_cmp`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp "method std::cmp::PartialOrd::partial_cmp") method, with the others generated from default implementations. However it remains possible to implement the others separately for types which do not have a total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 == false` (cf. IEEE 754-2008 section 5.11). `PartialOrd` requires your type to be [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") . If your type is [`Ord`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , you can implement [`partial_cmp`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp "method std::cmp::PartialOrd::partial_cmp") by using [`cmp`](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp "method std::cmp::Ord::cmp") : use std::cmp::Ordering; struct Person { id: u32, name: String, height: u32, } impl PartialOrd for Person { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Person { fn cmp(&self, other: &Self) -> Ordering { self.height.cmp(&other.height) } } impl PartialEq for Person { fn eq(&self, other: &Self) -> bool { self.height == other.height } } impl Eq for Person {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++struct+Person+%7B%0A++++++++id:+u32,%0A++++++++name:+String,%0A++++++++height:+u32,%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Person+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B%0A++++++++++++Some(self.cmp(other))%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Ord+for+Person+%7B%0A++++++++fn+cmp(%26self,+other:+%26Self)+-%3E+Ordering+%7B%0A++++++++++++self.height.cmp(%26other.height)%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+PartialEq+for+Person+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B%0A++++++++++++self.height+==+other.height%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Eq+for+Person+%7B%7D%0A%7D&edition=2024 "Run code") You may also find it useful to use [`partial_cmp`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp "method std::cmp::PartialOrd::partial_cmp") on your type’s fields. Here is an example of `Person` types who have a floating-point `height` field that is the only field to be used for sorting: use std::cmp::Ordering; struct Person { id: u32, name: String, height: f64, } impl PartialOrd for Person { fn partial_cmp(&self, other: &Self) -> Option { self.height.partial_cmp(&other.height) } } impl PartialEq for Person { fn eq(&self, other: &Self) -> bool { self.height == other.height } } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++struct+Person+%7B%0A++++++++id:+u32,%0A++++++++name:+String,%0A++++++++height:+f64,%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Person+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B%0A++++++++++++self.height.partial_cmp(%26other.height)%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+PartialEq+for+Person+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B%0A++++++++++++self.height+==+other.height%0A++++++++%7D%0A++++%7D%0A%7D&edition=2024 "Run code") ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples-of-incorrect-partialord-implementations) Examples of incorrect `PartialOrd` implementations use std::cmp::Ordering; #[derive(PartialEq, Debug)] struct Character { health: u32, experience: u32, } impl PartialOrd for Character { fn partial_cmp(&self, other: &Self) -> Option { Some(self.health.cmp(&other.health)) } } let a = Character { health: 10, experience: 5, }; let b = Character { health: 10, experience: 77, }; // Mistake: `PartialEq` and `PartialOrd` disagree with each other. assert_eq!(a.partial_cmp(&b).unwrap(), Ordering::Equal); // a == b according to `PartialOrd`. assert_ne!(a, b); // a != b according to `PartialEq`. [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++%23%5Bderive(PartialEq,+Debug)%5D%0A++++struct+Character+%7B%0A++++++++health:+u32,%0A++++++++experience:+u32,%0A++++%7D%0A++++%0A++++impl+PartialOrd+for+Character+%7B%0A++++++++fn+partial_cmp(%26self,+other:+%26Self)+-%3E+Option%3COrdering%3E+%7B%0A++++++++++++Some(self.health.cmp(%26other.health))%0A++++++++%7D%0A++++%7D%0A++++%0A++++let+a+=+Character+%7B%0A++++++++health:+10,%0A++++++++experience:+5,%0A++++%7D;%0A++++let+b+=+Character+%7B%0A++++++++health:+10,%0A++++++++experience:+77,%0A++++%7D;%0A++++%0A++++//+Mistake:+%60PartialEq%60+and+%60PartialOrd%60+disagree+with+each+other.%0A++++%0A++++assert_eq!(a.partial_cmp(%26b).unwrap(),+Ordering::Equal);+//+a+==+b+according+to+%60PartialOrd%60.%0A++++assert_ne!(a,+b);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples) Examples ------------------------------------------------------------------------------------- let x: u32 = 0; let y: u32 = 1; assert_eq!(x < y, true); assert_eq!(x.lt(&y), true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+x:+u32+=+0;%0A++++let+y:+u32+=+1;%0A++++%0A++++assert_eq!(x+%3C+y,+true);%0A++++assert_eq!(x.lt(%26y),+true);%0A%7D&edition=2024 "Run code") Required Methods[§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#required-methods) ----------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1383) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples-1) Examples use std::cmp::Ordering; let result = 1.0.partial_cmp(&2.0); assert_eq!(result, Some(Ordering::Less)); let result = 1.0.partial_cmp(&1.0); assert_eq!(result, Some(Ordering::Equal)); let result = 2.0.partial_cmp(&1.0); assert_eq!(result, Some(Ordering::Greater)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cmp::Ordering;%0A++++%0A++++let+result+=+1.0.partial_cmp(%262.0);%0A++++assert_eq!(result,+Some(Ordering::Less));%0A++++%0A++++let+result+=+1.0.partial_cmp(%261.0);%0A++++assert_eq!(result,+Some(Ordering::Equal));%0A++++%0A++++let+result+=+2.0.partial_cmp(%261.0);%0A++++assert_eq!(result,+Some(Ordering::Greater));%0A%7D&edition=2024 "Run code") When comparison is impossible: let result = f64::NAN.partial_cmp(&1.0); assert_eq!(result, None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++let+result+=+f64::NAN.partial_cmp(%261.0);%0A++++assert_eq!(result,+None);%0A%7D&edition=2024 "Run code") Provided Methods[§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#provided-methods) ----------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples-2) Examples assert_eq!(1.0 < 1.0, false); assert_eq!(1.0 < 2.0, true); assert_eq!(2.0 < 1.0, false); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1.0+%3C+1.0,+false);%0A++++assert_eq!(1.0+%3C+2.0,+true);%0A++++assert_eq!(2.0+%3C+1.0,+false);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples-3) Examples assert_eq!(1.0 <= 1.0, true); assert_eq!(1.0 <= 2.0, true); assert_eq!(2.0 <= 1.0, false); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1.0+%3C=+1.0,+true);%0A++++assert_eq!(1.0+%3C=+2.0,+true);%0A++++assert_eq!(2.0+%3C=+1.0,+false);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples-4) Examples assert_eq!(1.0 > 1.0, false); assert_eq!(1.0 > 2.0, false); assert_eq!(2.0 > 1.0, true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1.0+%3E+1.0,+false);%0A++++assert_eq!(1.0+%3E+2.0,+false);%0A++++assert_eq!(2.0+%3E+1.0,+true);%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. ##### [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#examples-5) Examples assert_eq!(1.0 >= 1.0, true); assert_eq!(1.0 >= 2.0, false); assert_eq!(2.0 >= 1.0, true); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++assert_eq!(1.0+%3E=+1.0,+true);%0A++++assert_eq!(1.0+%3E=+2.0,+false);%0A++++assert_eq!(2.0+%3E=+1.0,+true);%0A%7D&edition=2024 "Run code") Implementors[§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#implementors) --------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Char) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#971) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Infallible) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-ErrorKind) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-IpAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#31) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-SocketAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [SocketAddr](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html "enum std::net::SocketAddr") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#385) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Ordering) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1969) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-bool) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-char) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [char](https://doc.rust-lang.org/stable/std/primitive.char.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1978) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-f16) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [f16](https://doc.rust-lang.org/stable/std/primitive.f16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1978) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-f32) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1978) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-f64) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1978) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-f128) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [f128](https://doc.rust-lang.org/stable/std/primitive.f128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-i8) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [i8](https://doc.rust-lang.org/stable/std/primitive.i8.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-i16) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [i16](https://doc.rust-lang.org/stable/std/primitive.i16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-i32) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [i32](https://doc.rust-lang.org/stable/std/primitive.i32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-i64) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [i64](https://doc.rust-lang.org/stable/std/primitive.i64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-i128) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [i128](https://doc.rust-lang.org/stable/std/primitive.i128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-isize) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [isize](https://doc.rust-lang.org/stable/std/primitive.isize.html) [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2064) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-!) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [!](https://doc.rust-lang.org/stable/std/primitive.never.html) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/traits.rs.html#46) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-str) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [str](https://doc.rust-lang.org/stable/std/primitive.str.html) Implements comparison operations on strings. Strings are compared [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") by their byte values. This compares Unicode code points based on their positions in the code charts. This is not necessarily the same as “alphabetical” order, which varies by language and locale. Comparing strings according to culturally-accepted standards requires locale-specific data that is outside the scope of the `str` type. 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-u8) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-u16) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-u32) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-u64) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-u128) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1960) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-()) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [()](https://doc.rust-lang.org/stable/std/primitive.unit.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-usize) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/stdarch/crates/core_arch/src/x86/cpuid.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-CpuidResult) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [CpuidResult](https://doc.rust-lang.org/stable/core/core_arch/x86/cpuid/struct.CpuidResult.html "struct core::core_arch::x86::cpuid::CpuidResult") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#708) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-TypeId) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/bstr/traits.rs.html#17) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-ByteStr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#553) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-ByteString) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#670) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-CStr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [CStr](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/ffi/c_str.rs.html#104) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-CString) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [CString](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1513-1534) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-OsStr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#764-785) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-OsString) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#106) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Error) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") 1.33.0 · [Source](https://doc.rust-lang.org/stable/src/core/marker.rs.html#1024) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomPinned) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomPinned](https://doc.rust-lang.org/stable/std/marker/struct.PhantomPinned.html "struct std::marker::PhantomPinned") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1186) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Ipv4Addr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2180) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Ipv6Addr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#79) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-SocketAddrV4) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [SocketAddrV4](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html "struct std::net::SocketAddrV4") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#145) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-SocketAddrV6) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [SocketAddrV6](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html "struct std::net::SocketAddrV6") 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/panic/location.rs.html#72) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Location%3C'_%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Location](https://doc.rust-lang.org/stable/std/panic/struct.Location.html "struct std::panic::Location") <'\_> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3682-3687) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Path) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#2242-2247) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PathBuf) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") [Source](https://doc.rust-lang.org/stable/src/core/ptr/alignment.rs.html#222) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Alignment) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Alignment](https://doc.rust-lang.org/stable/std/ptr/struct.Alignment.html "struct std::ptr::Alignment") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#357) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-String) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Duration) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#155) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Instant) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#249) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-SystemTime) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1205) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CIpAddr%3E-for-Ipv4Addr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") \> for [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2199) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CIpAddr%3E-for-Ipv6Addr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") \> for [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1537-1542) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3Cstr%3E-for-OsStr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#788-793) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3Cstr%3E-for-OsString) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3857) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsStr%3E-for-Path) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3853) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsStr%3E-for-PathBuf) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3860) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-Path) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3856) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-PathBuf) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#1194) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CIpv4Addr%3E-for-IpAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#2188) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CIpv6Addr%3E-for-IpAddr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") \> for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3857) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPath%3E-for-OsStr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3860) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPath%3E-for-OsString) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3811) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPath%3E-for-PathBuf) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3853) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-OsStr) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3856) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-OsString) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3811) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-Path) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#500) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Component%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Component](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") <'a> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#135) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Prefix%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Prefix](https://doc.rust-lang.org/stable/std/path/enum.Prefix.html "enum std::path::Prefix") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomContravariantLifetime%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomContravariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariantLifetime.html "struct std::marker::PhantomContravariantLifetime") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomCovariantLifetime%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomCovariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariantLifetime.html "struct std::marker::PhantomCovariantLifetime") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomInvariantLifetime%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomInvariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariantLifetime.html "struct std::marker::PhantomInvariantLifetime") <'a> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#1019-1024) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Components%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Components](https://doc.rust-lang.org/stable/std/path/struct.Components.html "struct std::path::Components") <'a> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#456-461) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PrefixComponent%3C'a%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PrefixComponent](https://doc.rust-lang.org/stable/std/path/struct.PrefixComponent.html "struct std::path::PrefixComponent") <'a> [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#671) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26ByteStr%3E-for-Cow%3C'a,+str%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#670) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26ByteStr%3E-for-Cow%3C'a,+ByteStr%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#672) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26ByteStr%3E-for-Cow%3C'a,+%5Bu8%5D%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, \[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3858) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26OsStr%3E-for-Path) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3854) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26OsStr%3E-for-PathBuf) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3861) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26Path%3E-for-OsStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3863) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26Path%3E-for-OsString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3812) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26Path%3E-for-PathBuf) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#535) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26ByteStr%3E-for-ByteString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&[ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#541) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'_,+str%3E%3E-for-ByteString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \>> for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#540) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'_,+ByteStr%3E%3E-for-ByteString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \>> for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#542) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'_,+%5Bu8%5D%3E%3E-for-ByteString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, \[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>> for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#671) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+str%3E%3E-for-%26ByteStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \>> for &'a [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#670) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+ByteStr%3E%3E-for-%26ByteStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \>> for &'a [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3859) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+OsStr%3E%3E-for-Path) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \>> for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3855) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+OsStr%3E%3E-for-PathBuf) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \>> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3864) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+Path%3E%3E-for-OsStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \>> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3866) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+Path%3E%3E-for-OsString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \>> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3813) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+Path%3E%3E-for-Path) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \>> for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3815) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+Path%3E%3E-for-PathBuf) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \>> for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#672) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+%5Bu8%5D%3E%3E-for-%26ByteStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, \[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>> for &'a [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#534) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CByteStr%3E-for-ByteString) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#535) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CByteString%3E-for-%26ByteStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") \> for &[ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#541) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CByteString%3E-for-Cow%3C'_,+str%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, [str](https://doc.rust-lang.org/stable/std/primitive.str.html) \> [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#540) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CByteString%3E-for-Cow%3C'_,+ByteStr%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") \> [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#542) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CByteString%3E-for-Cow%3C'_,+%5Bu8%5D%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, \[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]> [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#534) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CByteString%3E-for-ByteStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") \> for [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3861) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsStr%3E-for-%26Path) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for &'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3864) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsStr%3E-for-Cow%3C'a,+Path%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3863) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-%26Path) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for &'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3866) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-Cow%3C'a,+Path%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3858) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPath%3E-for-%26OsStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for &'a [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3859) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPath%3E-for-Cow%3C'a,+OsStr%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3813) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPath%3E-for-Cow%3C'a,+Path%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3854) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-%26OsStr) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for &'a [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3812) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-%26Path) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for &'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3855) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-Cow%3C'a,+OsStr%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3815) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPathBuf%3E-for-Cow%3C'a,+Path%3E) ### impl<'a> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1592) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26OsStr%3E-for-OsString) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3862) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26Path%3E-for-Cow%3C'b,+OsStr%3E) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'b, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1594) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26OsStr%3E-for-Cow%3C'a,+OsStr%3E) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'b [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3865) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26OsStr%3E-for-Cow%3C'a,+Path%3E) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'b [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3814) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26Path%3E-for-Cow%3C'a,+Path%3E) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <&'b [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1594) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+OsStr%3E%3E-for-%26OsStr) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \>> for &'b [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1593) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+OsStr%3E%3E-for-OsStr) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \>> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1595) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+OsStr%3E%3E-for-OsString) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \>> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3865) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+Path%3E%3E-for-%26OsStr) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \>> for &'b [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3814) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'a,+Path%3E%3E-for-%26Path) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") \>> for &'b [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3862) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CCow%3C'b,+OsStr%3E%3E-for-%26Path) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'b, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \>> for &'a [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1593) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsStr%3E-for-Cow%3C'a,+OsStr%3E) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1591) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsStr%3E-for-OsString) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1592) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-%26OsStr) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for &'a [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1595) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-Cow%3C'a,+OsStr%3E) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") \> 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1591) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3COsString%3E-for-OsStr) ### impl<'a, 'b> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") \> for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#389-391) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Cow%3C'a,+B%3E) ### impl<'a, B> [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'a, B> where B: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2099-2101) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26B%3E-for-%26A) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[&B](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> for [&A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , B: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2174-2176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3C%26mut+B%3E-for-%26mut+A) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[&mut B](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> for [&mut A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , B: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/ptr/metadata.rs.html#251) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-DynMetadata%3CDyn%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [DynMetadata](https://doc.rust-lang.org/stable/std/ptr/struct.DynMetadata.html "struct std::ptr::DynMetadata") where Dyn: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.4.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mod.rs.html#2569) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-F) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for F where F: [FnPtr](https://doc.rust-lang.org/stable/std/marker/trait.FnPtr.html "trait std::marker::FnPtr") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/map.rs.html#2425) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-BTreeMap%3CK,+V,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [BTreeMap](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") where K: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , V: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 1.41.0 · [Source](https://doc.rust-lang.org/stable/src/core/pin.rs.html#1122-1124) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CPin%3CQ%3E%3E-for-Pin%3CPtr%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") > for [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") where Ptr: [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") , Q: [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") , ::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "type std::ops::Deref::Target") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "type std::ops::Deref::Target") \>, 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/option.rs.html#2373) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Option%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/task/poll.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Poll%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Poll](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/const_ptr.rs.html#1599) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-*const+T) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [\*const T](https://doc.rust-lang.org/stable/std/primitive.pointer.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Pointer comparison is by address, as produced by the `[`<\*const T>::addr`](pointer::addr)` method. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mut_ptr.rs.html#2032) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-*mut+T) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [\*mut T](https://doc.rust-lang.org/stable/std/primitive.pointer.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Pointer comparison is by address, as produced by the [`<*mut T>::addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.addr "method pointer::addr") method. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/cmp.rs.html#50) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-%5BT%5D) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [\[T\]](https://doc.rust-lang.org/stable/std/primitive.slice.html) where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , Implements comparison of slices [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") . 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/tuple.rs.html#238) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-(T,)) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [(T₁, T₂, …, Tₙ)](https://doc.rust-lang.org/stable/std/primitive.tuple.html#trait-implementations-1) where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , This trait is implemented for tuples up to twelve items long. 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#358) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Cell%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Cell](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#1453) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-RefCell%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [RefCell](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomContravariant%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomContravariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariant.html "struct std::marker::PhantomContravariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomCovariant%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomCovariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariant.html "struct std::marker::PhantomCovariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/marker.rs.html#841) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomData%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomData](https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html "struct std::marker::PhantomData") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-PhantomInvariant%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [PhantomInvariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariant.html "struct std::marker::PhantomInvariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.20.0 · [Source](https://doc.rust-lang.org/stable/src/core/mem/manually_drop.rs.html#155) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-ManuallyDrop%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [ManuallyDrop](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "struct std::mem::ManuallyDrop") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/num/nonzero.rs.html#228-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-NonZero%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [NonZero](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html "struct std::num::NonZero") where T: [ZeroablePrimitive](https://doc.rust-lang.org/stable/std/num/trait.ZeroablePrimitive.html "trait std::num::ZeroablePrimitive") + [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , 1.74.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/saturating.rs.html#35) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Saturating%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Saturating](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html "struct std::num::Saturating") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/wrapping.rs.html#40) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Wrapping%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Wrapping](https://doc.rust-lang.org/stable/std/num/struct.Wrapping.html "struct std::num::Wrapping") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , 1.25.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/non_null.rs.html#1701) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-NonNull%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.19.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#675) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Reverse%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Reverse](https://doc.rust-lang.org/stable/std/cmp/struct.Reverse.html "struct std::cmp::Reverse") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/vec/mod.rs.html#4016-4020) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CVec%3CT,+A2%3E%3E-for-Vec%3CT,+A1%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") > for [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , A1: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , A2: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , Implements comparison of vectors, [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") . 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed.rs.html#1861) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Box%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/set.rs.html#103) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-BTreeSet%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [BTreeSet](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html "struct std::collections::BTreeSet") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/linked_list.rs.html#2136) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-LinkedList%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [LinkedList](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/vec_deque/mod.rs.html#3037) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-VecDeque%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [VecDeque](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#2495) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Rc%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Rc](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#3850) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-UniqueRc%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [UniqueRc](https://doc.rust-lang.org/stable/std/rc/struct.UniqueRc.html "struct std::rc::UniqueRc") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#3404) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Arc%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Arc](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#4262) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-UniqueArc%3CT,+A%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [UniqueArc](https://doc.rust-lang.org/stable/std/sync/struct.UniqueArc.html "struct std::sync::UniqueArc") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/result.rs.html#553) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Result%3CT,+E%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , E: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , [Source](https://doc.rust-lang.org/stable/src/core/sync/exclusive.rs.html#297-300) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd%3CExclusive%3CU%3E%3E-for-Exclusive%3CT%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <[Exclusive](https://doc.rust-lang.org/stable/std/sync/struct.Exclusive.html "struct std::sync::Exclusive") > for [Exclusive](https://doc.rust-lang.org/stable/std/sync/struct.Exclusive.html "struct std::sync::Exclusive") where T: [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") + [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , U: [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/array/mod.rs.html#406) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-%5BT;+N%5D) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [\[T; N\]](https://doc.rust-lang.org/stable/std/primitive.array.html) where T: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , Implements comparison of arrays [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") . [Source](https://doc.rust-lang.org/stable/src/core/portable-simd/crates/core_simd/src/masks.rs.html#420-423) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Mask%3CT,+N%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Mask](https://doc.rust-lang.org/stable/std/simd/struct.Mask.html "struct std::simd::Mask") where T: [MaskElement](https://doc.rust-lang.org/stable/std/simd/trait.MaskElement.html "trait std::simd::MaskElement") + [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , [LaneCount](https://doc.rust-lang.org/stable/std/simd/struct.LaneCount.html "struct std::simd::LaneCount") : [SupportedLaneCount](https://doc.rust-lang.org/stable/std/simd/trait.SupportedLaneCount.html "trait std::simd::SupportedLaneCount") , [Source](https://doc.rust-lang.org/stable/src/core/portable-simd/crates/core_simd/src/vector.rs.html#952-955) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-Simd%3CT,+N%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Simd](https://doc.rust-lang.org/stable/std/simd/struct.Simd.html "struct std::simd::Simd") where [LaneCount](https://doc.rust-lang.org/stable/std/simd/struct.LaneCount.html "struct std::simd::LaneCount") : [SupportedLaneCount](https://doc.rust-lang.org/stable/std/simd/trait.SupportedLaneCount.html "trait std::simd::SupportedLaneCount") , T: [SimdElement](https://doc.rust-lang.org/stable/std/simd/trait.SimdElement.html "trait std::simd::SimdElement") + [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , Lexicographic order. For the SIMD elementwise minimum and maximum, use simd\_min and simd\_max instead. [Source](https://doc.rust-lang.org/stable/src/core/ops/coroutine.rs.html#8) [§](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#impl-PartialOrd-for-CoroutineState%3CY,+R%3E) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [CoroutineState](https://doc.rust-lang.org/stable/std/ops/enum.CoroutineState.html "enum std::ops::CoroutineState") where Y: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , R: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , --- # Eq in std::cmp - Rust [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#) -------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[cmp](https://doc.rust-lang.org/stable/std/cmp/index.html) Trait Eq Copy item path ======================= 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#338) pub trait Eq: PartialEq { } Expand description Trait for comparisons corresponding to [equivalence relations](https://en.wikipedia.org/wiki/Equivalence_relation) . The primary difference to [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") is the additional requirement for reflexivity. A type that implements [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") guarantees that for all `a`, `b` and `c`: * symmetric: `a == b` implies `b == a` and `a != b` implies `!(a == b)` * transitive: `a == b` and `b == c` implies `a == c` `Eq`, which builds on top of [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") also implies: * reflexive: `a == a` This property cannot be checked by the compiler, and therefore `Eq` is a trait without methods. Violating this property is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do _not_ result in undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these methods. Floating point types such as [`f32`](https://doc.rust-lang.org/stable/std/primitive.f32.html "primitive f32") and [`f64`](https://doc.rust-lang.org/stable/std/primitive.f64.html "primitive f64") implement only [`PartialEq`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") but _not_ `Eq` because `NaN` != `NaN`. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#derivable) Derivable This trait can be used with `#[derive]`. When `derive`d, because `Eq` has no extra methods, it is only informing the compiler that this is an equivalence relation rather than a partial equivalence relation. Note that the `derive` strategy requires all fields are `Eq`, which isn’t always desired. ### [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#how-can-i-implement-eq) How can I implement `Eq`? If you cannot use the `derive` strategy, specify that your type implements `Eq`, which has no extra methods: enum BookFormat { Paperback, Hardback, Ebook, } struct Book { isbn: i32, format: BookFormat, } impl PartialEq for Book { fn eq(&self, other: &Self) -> bool { self.isbn == other.isbn } } impl Eq for Book {} [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++enum+BookFormat+%7B%0A++++++++Paperback,%0A++++++++Hardback,%0A++++++++Ebook,%0A++++%7D%0A++++%0A++++struct+Book+%7B%0A++++++++isbn:+i32,%0A++++++++format:+BookFormat,%0A++++%7D%0A++++%0A++++impl+PartialEq+for+Book+%7B%0A++++++++fn+eq(%26self,+other:+%26Self)+-%3E+bool+%7B%0A++++++++++++self.isbn+==+other.isbn%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Eq+for+Book+%7B%7D%0A%7D&edition=2024 "Run code") Dyn Compatibility[§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#dyn-compatibility) ----------------------------------------------------------------------------------------------- This trait is **not** [dyn compatible](https://doc.rust-lang.org/1.92.0/reference/items/traits.html#dyn-compatibility) . _In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe._ Implementors[§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#implementors) ------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/ascii/ascii_char.rs.html#58) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Char) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [AsciiChar](https://doc.rust-lang.org/stable/std/ascii/enum.Char.html "enum std::ascii::Char") 1.65.0 · [Source](https://doc.rust-lang.org/stable/src/std/backtrace.rs.html#116) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-BacktraceStatus) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [BacktraceStatus](https://doc.rust-lang.org/stable/std/backtrace/enum.BacktraceStatus.html "enum std::backtrace::BacktraceStatus") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#93) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TryReserveErrorKind) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryReserveErrorKind](https://doc.rust-lang.org/stable/std/collections/enum.TryReserveErrorKind.html "enum std::collections::TryReserveErrorKind") 1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#967) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Infallible) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/env.rs.html#271) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-VarError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [VarError](https://doc.rust-lang.org/stable/std/env/enum.VarError.html "enum std::env::VarError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#125) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FromBytesWithNulError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FromBytesWithNulError](https://doc.rust-lang.org/stable/std/ffi/enum.FromBytesWithNulError.html "enum std::ffi::FromBytesWithNulError") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#24) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Alignment) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::fmt::[Alignment](https://doc.rust-lang.org/stable/std/fmt/enum.Alignment.html "enum std::fmt::Alignment") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#270) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-DebugAsHex) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [DebugAsHex](https://doc.rust-lang.org/stable/std/fmt/enum.DebugAsHex.html "enum std::fmt::DebugAsHex") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#259) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Sign) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Sign](https://doc.rust-lang.org/stable/std/fmt/enum.Sign.html "enum std::fmt::Sign") [Source](https://doc.rust-lang.org/stable/src/core/intrinsics/mod.rs.html#74) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-AtomicOrdering) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [AtomicOrdering](https://doc.rust-lang.org/stable/std/intrinsics/enum.AtomicOrdering.html "enum std::intrinsics::AtomicOrdering") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/error.rs.html#223) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ErrorKind) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ErrorKind](https://doc.rust-lang.org/stable/std/io/enum.ErrorKind.html "enum std::io::ErrorKind") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#2182) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SeekFrom) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SeekFrom](https://doc.rust-lang.org/stable/std/io/enum.SeekFrom.html "enum std::io::SeekFrom") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#29) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-IpAddr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [IpAddr](https://doc.rust-lang.org/stable/std/net/enum.IpAddr.html "enum std::net::IpAddr") [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#215) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Ipv6MulticastScope) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Ipv6MulticastScope](https://doc.rust-lang.org/stable/std/net/enum.Ipv6MulticastScope.html "enum std::net::Ipv6MulticastScope") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/net/mod.rs.html#50) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Shutdown) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Shutdown](https://doc.rust-lang.org/stable/std/net/enum.Shutdown.html "enum std::net::Shutdown") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#31) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SocketAddr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SocketAddr](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html "enum std::net::SocketAddr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/mod.rs.html#1337) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FpCategory) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FpCategory](https://doc.rust-lang.org/stable/std/num/enum.FpCategory.html "enum std::num::FpCategory") 1.55.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#81) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-IntErrorKind) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [IntErrorKind](https://doc.rust-lang.org/stable/std/num/enum.IntErrorKind.html "enum std::num::IntErrorKind") [Source](https://doc.rust-lang.org/stable/src/std/panic.rs.html#432) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-BacktraceStyle) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [BacktraceStyle](https://doc.rust-lang.org/stable/std/panic/enum.BacktraceStyle.html "enum std::panic::BacktraceStyle") 1.86.0 · [Source](https://doc.rust-lang.org/stable/src/core/slice/mod.rs.html#5215) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-GetDisjointMutError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [GetDisjointMutError](https://doc.rust-lang.org/stable/std/slice/enum.GetDisjointMutError.html "enum std::slice::GetDisjointMutError") [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#184) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SearchStep) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SearchStep](https://doc.rust-lang.org/stable/std/str/pattern/enum.SearchStep.html "enum std::str::pattern::SearchStep") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/sync/atomic.rs.html#436) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Ordering) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::sync::atomic::[Ordering](https://doc.rust-lang.org/stable/std/sync/atomic/enum.Ordering.html "enum std::sync::atomic::Ordering") 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#444) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RecvTimeoutError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#425) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TryRecvError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#385) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Ordering-1) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::cmp::[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-bool) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-char) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [char](https://doc.rust-lang.org/stable/std/primitive.char.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-i8) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [i8](https://doc.rust-lang.org/stable/std/primitive.i8.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-i16) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [i16](https://doc.rust-lang.org/stable/std/primitive.i16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-i32) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [i32](https://doc.rust-lang.org/stable/std/primitive.i32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-i64) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [i64](https://doc.rust-lang.org/stable/std/primitive.i64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-i128) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [i128](https://doc.rust-lang.org/stable/std/primitive.i128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-isize) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [isize](https://doc.rust-lang.org/stable/std/primitive.isize.html) [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2060) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-!) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [!](https://doc.rust-lang.org/stable/std/primitive.never.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/str/traits.rs.html#36) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-str) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [str](https://doc.rust-lang.org/stable/std/primitive.str.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-u8) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-u16) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-u32) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-u64) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-u128) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-()) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [()](https://doc.rust-lang.org/stable/std/primitive.unit.html) 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1897) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-usize) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/stdarch/crates/core_arch/src/x86/cpuid.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-CpuidResult) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [CpuidResult](https://doc.rust-lang.org/stable/core/core_arch/x86/cpuid/struct.CpuidResult.html "struct core::core_arch::x86::cpuid::CpuidResult") [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#31) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-AllocError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/alloc/layout.rs.html#38) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Layout) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/alloc/layout.rs.html#548) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-LayoutError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [LayoutError](https://doc.rust-lang.org/stable/std/alloc/struct.LayoutError.html "struct std::alloc::LayoutError") 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#709) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TypeId) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") [Source](https://doc.rust-lang.org/stable/src/core/bstr/traits.rs.html#33) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ByteStr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ByteStr](https://doc.rust-lang.org/stable/std/bstr/struct.ByteStr.html "struct std::bstr::ByteStr") [Source](https://doc.rust-lang.org/stable/src/alloc/bstr.rs.html#468) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ByteString) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ByteString](https://doc.rust-lang.org/stable/std/bstr/struct.ByteString.html "struct std::bstr::ByteString") 1.34.0 · [Source](https://doc.rust-lang.org/stable/src/core/char/convert.rs.html#274) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-CharTryFromError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [CharTryFromError](https://doc.rust-lang.org/stable/std/char/struct.CharTryFromError.html "struct std::char::CharTryFromError") 1.9.0 · [Source](https://doc.rust-lang.org/stable/src/core/char/decode.rs.html#27) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-DecodeUtf16Error) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [DecodeUtf16Error](https://doc.rust-lang.org/stable/std/char/struct.DecodeUtf16Error.html "struct std::char::DecodeUtf16Error") 1.20.0 · [Source](https://doc.rust-lang.org/stable/src/core/char/convert.rs.html#194) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ParseCharError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ParseCharError](https://doc.rust-lang.org/stable/std/char/struct.ParseCharError.html "struct std::char::ParseCharError") 1.59.0 · [Source](https://doc.rust-lang.org/stable/src/core/char/mod.rs.html#594) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TryFromCharError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryFromCharError](https://doc.rust-lang.org/stable/std/char/struct.TryFromCharError.html "struct std::char::TryFromCharError") [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/map.rs.html#3528) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-UnorderedKeyError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [UnorderedKeyError](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.UnorderedKeyError.html "struct std::collections::btree_map::UnorderedKeyError") 1.57.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/mod.rs.html#67) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TryReserveError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryReserveError](https://doc.rust-lang.org/stable/std/collections/struct.TryReserveError.html "struct std::collections::TryReserveError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#91) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-CStr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [CStr](https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html "struct std::ffi::CStr") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/ffi/c_str.rs.html#104) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-CString) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [CString](https://doc.rust-lang.org/stable/std/ffi/struct.CString.html "struct std::ffi::CString") 1.69.0 · [Source](https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#158) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FromBytesUntilNulError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FromBytesUntilNulError](https://doc.rust-lang.org/stable/std/ffi/struct.FromBytesUntilNulError.html "struct std::ffi::FromBytesUntilNulError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/ffi/c_str.rs.html#154) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FromVecWithNulError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FromVecWithNulError](https://doc.rust-lang.org/stable/std/ffi/struct.FromVecWithNulError.html "struct std::ffi::FromVecWithNulError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/ffi/c_str.rs.html#220) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-IntoStringError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [IntoStringError](https://doc.rust-lang.org/stable/std/ffi/struct.IntoStringError.html "struct std::ffi::IntoStringError") 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/ffi/c_str.rs.html#129) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-NulError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [NulError](https://doc.rust-lang.org/stable/std/ffi/struct.NulError.html "struct std::ffi::NulError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#1510) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-OsStr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [OsStr](https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html "struct std::ffi::OsStr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/ffi/os_str.rs.html#761) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-OsString) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html "struct std::ffi::OsString") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#106) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Error) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") [Source](https://doc.rust-lang.org/stable/src/core/fmt/mod.rs.html#283) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FormattingOptions) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FormattingOptions](https://doc.rust-lang.org/stable/std/fmt/struct.FormattingOptions.html "struct std::fmt::FormattingOptions") 1.1.0 · [Source](https://doc.rust-lang.org/stable/src/std/fs.rs.html#262) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FileType) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FileType](https://doc.rust-lang.org/stable/std/fs/struct.FileType.html "struct std::fs::FileType") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/fs.rs.html#254) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Permissions) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Permissions](https://doc.rust-lang.org/stable/std/fs/struct.Permissions.html "struct std::fs::Permissions") 1.33.0 · [Source](https://doc.rust-lang.org/stable/src/core/marker.rs.html#1024) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomPinned) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomPinned](https://doc.rust-lang.org/stable/std/marker/struct.PhantomPinned.html "struct std::marker::PhantomPinned") [Source](https://doc.rust-lang.org/stable/src/core/mem/transmutability.rs.html#150) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Assume) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Assume](https://doc.rust-lang.org/stable/std/mem/struct.Assume.html "struct std::mem::Assume") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/parser.rs.html#495) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-AddrParseError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [AddrParseError](https://doc.rust-lang.org/stable/std/net/struct.AddrParseError.html "struct std::net::AddrParseError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#71) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Ipv4Addr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Ipv4Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv4Addr.html "struct std::net::Ipv4Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/ip_addr.rs.html#164) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Ipv6Addr) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Ipv6Addr](https://doc.rust-lang.org/stable/std/net/struct.Ipv6Addr.html "struct std::net::Ipv6Addr") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#79) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SocketAddrV4) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SocketAddrV4](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html "struct std::net::SocketAddrV4") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/net/socket_addr.rs.html#145) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SocketAddrV6) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SocketAddrV6](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html "struct std::net::SocketAddrV6") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/dec2flt/mod.rs.html#209) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ParseFloatError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ParseFloatError](https://doc.rust-lang.org/stable/std/num/struct.ParseFloatError.html "struct std::num::ParseFloatError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#63) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ParseIntError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ParseIntError](https://doc.rust-lang.org/stable/std/num/struct.ParseIntError.html "struct std::num::ParseIntError") 1.34.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/error.rs.html#9) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TryFromIntError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryFromIntError](https://doc.rust-lang.org/stable/std/num/struct.TryFromIntError.html "struct std::num::TryFromIntError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#41) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeFull) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RangeFull](https://doc.rust-lang.org/stable/std/ops/struct.RangeFull.html "struct std::ops::RangeFull") [Source](https://doc.rust-lang.org/stable/src/std/os/unix/net/ucred.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-UCred) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [UCred](https://doc.rust-lang.org/stable/std/os/unix/net/struct.UCred.html "struct std::os::unix::net::UCred") Available on **Unix** only. 1.63.0 · [Source](https://doc.rust-lang.org/stable/src/std/os/windows/io/handle.rs.html#284) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-InvalidHandleError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [InvalidHandleError](https://doc.rust-lang.org/stable/std/os/windows/io/struct.InvalidHandleError.html "struct std::os::windows::io::InvalidHandleError") Available on **Windows** only. 1.63.0 · [Source](https://doc.rust-lang.org/stable/src/std/os/windows/io/handle.rs.html#266) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-NullHandleError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [NullHandleError](https://doc.rust-lang.org/stable/std/os/windows/io/struct.NullHandleError.html "struct std::os::windows::io::NullHandleError") Available on **Windows** only. 1.10.0 · [Source](https://doc.rust-lang.org/stable/src/core/panic/location.rs.html#59) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Location%3C'_%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Location](https://doc.rust-lang.org/stable/std/panic/struct.Location.html "struct std::panic::Location") <'\_> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#1016) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Components%3C'_%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Components](https://doc.rust-lang.org/stable/std/path/struct.Components.html "struct std::path::Components") <'\_> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#3679) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Path) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Path](https://doc.rust-lang.org/stable/std/path/struct.Path.html "struct std::path::Path") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#2239) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PathBuf) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PathBuf](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html "struct std::path::PathBuf") 1.7.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#2313) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-StripPrefixError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [StripPrefixError](https://doc.rust-lang.org/stable/std/path/struct.StripPrefixError.html "struct std::path::StripPrefixError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/process.rs.html#1790) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ExitStatus) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ExitStatus](https://doc.rust-lang.org/stable/std/process/struct.ExitStatus.html "struct std::process::ExitStatus") [Source](https://doc.rust-lang.org/stable/src/std/process.rs.html#1933) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ExitStatusError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ExitStatusError](https://doc.rust-lang.org/stable/std/process/struct.ExitStatusError.html "struct std::process::ExitStatusError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/process.rs.html#1326) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Output) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Output](https://doc.rust-lang.org/stable/std/process/struct.Output.html "struct std::process::Output") [Source](https://doc.rust-lang.org/stable/src/core/ptr/alignment.rs.html#13) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Alignment-1) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::ptr::[Alignment](https://doc.rust-lang.org/stable/std/ptr/struct.Alignment.html "struct std::ptr::Alignment") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/error.rs.html#132) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ParseBoolError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ParseBoolError](https://doc.rust-lang.org/stable/std/str/struct.ParseBoolError.html "struct std::str::ParseBoolError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/error.rs.html#45) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Utf8Error) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Utf8Error](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html "struct std::str::Utf8Error") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#397) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-FromUtf8Error) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [FromUtf8Error](https://doc.rust-lang.org/stable/std/string/struct.FromUtf8Error.html "struct std::string::FromUtf8Error") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#357) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-String) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RecvError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mod.rs.html#250) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-WaitTimeoutResult) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [WaitTimeoutResult](https://doc.rust-lang.org/stable/std/sync/struct.WaitTimeoutResult.html "struct std::sync::WaitTimeoutResult") 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#405) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-AccessError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [AccessError](https://doc.rust-lang.org/stable/std/thread/struct.AccessError.html "struct std::thread::AccessError") 1.19.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/mod.rs.html#1230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ThreadId) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ThreadId](https://doc.rust-lang.org/stable/std/thread/struct.ThreadId.html "struct std::thread::ThreadId") 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Duration) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#155) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Instant) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#249) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SystemTime) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") 1.66.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1478) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TryFromFloatSecsError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TryFromFloatSecsError](https://doc.rust-lang.org/stable/std/time/struct.TryFromFloatSecsError.html "struct std::time::TryFromFloatSecsError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#500) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Component%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Component](https://doc.rust-lang.org/stable/std/path/enum.Component.html "enum std::path::Component") <'a> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#135) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Prefix%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Prefix](https://doc.rust-lang.org/stable/std/path/enum.Prefix.html "enum std::path::Prefix") <'a> [Source](https://doc.rust-lang.org/stable/src/core/str/pattern.rs.html#173) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Utf8Pattern%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Utf8Pattern](https://doc.rust-lang.org/stable/std/str/pattern/enum.Utf8Pattern.html "enum std::str::pattern::Utf8Pattern") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomContravariantLifetime%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomContravariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariantLifetime.html "struct std::marker::PhantomContravariantLifetime") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomCovariantLifetime%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomCovariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariantLifetime.html "struct std::marker::PhantomCovariantLifetime") <'a> [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#126-176) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomInvariantLifetime%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomInvariantLifetime](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariantLifetime.html "struct std::marker::PhantomInvariantLifetime") <'a> 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/path.rs.html#417) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PrefixComponent%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PrefixComponent](https://doc.rust-lang.org/stable/std/path/struct.PrefixComponent.html "struct std::path::PrefixComponent") <'a> 1.79.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/lossy.rs.html#70) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Utf8Chunk%3C'a%3E) ### impl<'a> [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Utf8Chunk](https://doc.rust-lang.org/stable/std/str/struct.Utf8Chunk.html "struct std::str::Utf8Chunk") <'a> 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2153) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-%26A) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [&A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#2228) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-%26mut+A) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [&mut A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#363) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Cow%3C'_,+B%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Cow](https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html "enum std::borrow::Cow") <'\_, B> where B: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.55.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/ops/control_flow.rs.html#87) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ControlFlow%3CB,+C%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ControlFlow](https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html "enum std::ops::ControlFlow") where B: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , C: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/core/ptr/metadata.rs.html#234) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-DynMetadata%3CDyn%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [DynMetadata](https://doc.rust-lang.org/stable/std/ptr/struct.DynMetadata.html "struct std::ptr::DynMetadata") where Dyn: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.4.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mod.rs.html#2566) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-F) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for F where F: [FnPtr](https://doc.rust-lang.org/stable/std/marker/trait.FnPtr.html "trait std::marker::FnPtr") , 1.29.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#800) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-BuildHasherDefault%3CH%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [BuildHasherDefault](https://doc.rust-lang.org/stable/std/hash/struct.BuildHasherDefault.html "struct std::hash::BuildHasherDefault") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#78) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Range%3CIdx%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::ops::[Range](https://doc.rust-lang.org/stable/std/ops/struct.Range.html "struct std::ops::Range") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#187) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeFrom%3CIdx%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::ops::[RangeFrom](https://doc.rust-lang.org/stable/std/ops/struct.RangeFrom.html "struct std::ops::RangeFrom") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#343) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeInclusive%3CIdx%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::ops::[RangeInclusive](https://doc.rust-lang.org/stable/std/ops/struct.RangeInclusive.html "struct std::ops::RangeInclusive") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#269) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeTo%3CIdx%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RangeTo](https://doc.rust-lang.org/stable/std/ops/struct.RangeTo.html "struct std::ops::RangeTo") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#590) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeToInclusive%3CIdx%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::ops::[RangeToInclusive](https://doc.rust-lang.org/stable/std/ops/struct.RangeToInclusive.html "struct std::ops::RangeToInclusive") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/core/range.rs.html#53) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Range%3CIdx%3E-1) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::range::[Range](https://doc.rust-lang.org/stable/std/range/struct.Range.html "struct std::range::Range") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/core/range.rs.html#429) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeFrom%3CIdx%3E-1) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::range::[RangeFrom](https://doc.rust-lang.org/stable/std/range/struct.RangeFrom.html "struct std::range::RangeFrom") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/core/range.rs.html#228) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeInclusive%3CIdx%3E-1) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::range::[RangeInclusive](https://doc.rust-lang.org/stable/std/range/struct.RangeInclusive.html "struct std::range::RangeInclusive") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/core/range.rs.html#590) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RangeToInclusive%3CIdx%3E-1) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for std::range::[RangeToInclusive](https://doc.rust-lang.org/stable/std/range/struct.RangeToInclusive.html "struct std::range::RangeToInclusive") where Idx: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/map.rs.html#2422) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-BTreeMap%3CK,+V,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [BTreeMap](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html "struct std::collections::BTreeMap") where K: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , V: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/collections/hash/map.rs.html#1335-1341) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-HashMap%3CK,+V,+S%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [HashMap](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html "struct std::collections::HashMap") where K: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") , V: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , S: [BuildHasher](https://doc.rust-lang.org/stable/std/hash/trait.BuildHasher.html "trait std::hash::BuildHasher") , 1.41.0 · [Source](https://doc.rust-lang.org/stable/src/core/pin.rs.html#1119) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Pin%3CPtr%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Pin](https://doc.rust-lang.org/stable/std/pin/struct.Pin.html "struct std::pin::Pin") where Ptr: [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") , ::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "type std::ops::Deref::Target") : [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.17.0 · [Source](https://doc.rust-lang.org/stable/src/core/ops/range.rs.html#671) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Bound%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Bound](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html "enum std::ops::Bound") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/option.rs.html#594) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Option%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/task/poll.rs.html#11) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Poll%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Poll](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/const_ptr.rs.html#1579) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-*const+T) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [\*const T](https://doc.rust-lang.org/stable/std/primitive.pointer.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Pointer equality is an equivalence relation. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mut_ptr.rs.html#2012) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-*mut+T) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [\*mut T](https://doc.rust-lang.org/stable/std/primitive.pointer.html) where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Pointer equality is an equivalence relation. 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/slice/cmp.rs.html#27) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-%5BT%5D) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [\[T\]](https://doc.rust-lang.org/stable/std/primitive.slice.html) where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/tuple.rs.html#238) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-(T,)) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [(T₁, T₂, …, Tₙ)](https://doc.rust-lang.org/stable/std/primitive.tuple.html#trait-implementations-1) where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , This trait is implemented for tuples up to twelve items long. 1.2.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#355) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Cell%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Cell](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , 1.70.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell/once.rs.html#395) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-OnceCell%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [OnceCell](https://doc.rust-lang.org/stable/std/cell/struct.OnceCell.html "struct std::cell::OnceCell") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.2.0 · [Source](https://doc.rust-lang.org/stable/src/core/cell.rs.html#1450) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-RefCell%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RefCell](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomContravariant%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomContravariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomContravariant.html "struct std::marker::PhantomContravariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomCovariant%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomCovariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomCovariant.html "struct std::marker::PhantomCovariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/marker.rs.html#838) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomData%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomData](https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html "struct std::marker::PhantomData") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/marker/variance.rs.html#178-230) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-PhantomInvariant%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [PhantomInvariant](https://doc.rust-lang.org/stable/std/marker/struct.PhantomInvariant.html "struct std::marker::PhantomInvariant") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/mem/mod.rs.html#1081) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Discriminant%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Discriminant](https://doc.rust-lang.org/stable/std/mem/struct.Discriminant.html "struct std::mem::Discriminant") 1.20.0 · [Source](https://doc.rust-lang.org/stable/src/core/mem/manually_drop.rs.html#155) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-ManuallyDrop%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [ManuallyDrop](https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html "struct std::mem::ManuallyDrop") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/num/nonzero.rs.html#224) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-NonZero%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [NonZero](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html "struct std::num::NonZero") where T: [ZeroablePrimitive](https://doc.rust-lang.org/stable/std/num/trait.ZeroablePrimitive.html "trait std::num::ZeroablePrimitive") + [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.74.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/saturating.rs.html#35) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Saturating%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Saturating](https://doc.rust-lang.org/stable/std/num/struct.Saturating.html "struct std::num::Saturating") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/num/wrapping.rs.html#40) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Wrapping%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Wrapping](https://doc.rust-lang.org/stable/std/num/struct.Wrapping.html "struct std::num::Wrapping") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.25.0 · [Source](https://doc.rust-lang.org/stable/src/core/ptr/non_null.rs.html#1680) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-NonNull%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/sync/exclusive.rs.html#283) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Exclusive%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Exclusive](https://doc.rust-lang.org/stable/std/sync/struct.Exclusive.html "struct std::sync::Exclusive") where T: [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") + [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 1.19.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#668) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Reverse%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Reverse](https://doc.rust-lang.org/stable/std/cmp/struct.Reverse.html "struct std::cmp::Reverse") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/boxed.rs.html#1893) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Box%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Box](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html "struct std::boxed::Box") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/btree/set.rs.html#100) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-BTreeSet%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [BTreeSet](https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html "struct std::collections::BTreeSet") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/linked_list.rs.html#2133) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-LinkedList%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [LinkedList](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html "struct std::collections::LinkedList") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/collections/vec_deque/mod.rs.html#3027) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-VecDeque%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [VecDeque](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html "struct std::collections::VecDeque") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#2492) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Rc%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Rc](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html "struct std::rc::Rc") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/rc.rs.html#3972) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-UniqueRc%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [UniqueRc](https://doc.rust-lang.org/stable/std/rc/struct.UniqueRc.html "struct std::rc::UniqueRc") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#3512) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Arc%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Arc](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html "struct std::sync::Arc") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , [Source](https://doc.rust-lang.org/stable/src/alloc/sync.rs.html#4384) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-UniqueArc%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [UniqueArc](https://doc.rust-lang.org/stable/std/sync/struct.UniqueArc.html "struct std::sync::UniqueArc") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/alloc/vec/mod.rs.html#4029) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Vec%3CT,+A%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Vec](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html "struct std::vec::Vec") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/118304 "Tracking issue for derive_const") ) · [Source](https://doc.rust-lang.org/stable/src/core/result.rs.html#553) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Result%3CT,+E%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , E: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/collections/hash/set.rs.html#1042-1047) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-HashSet%3CT,+S%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [HashSet](https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html "struct std::collections::HashSet") where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") + [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") , S: [BuildHasher](https://doc.rust-lang.org/stable/std/hash/trait.BuildHasher.html "trait std::hash::BuildHasher") , 1.0.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143800 "Tracking issue for const_cmp") ) · [Source](https://doc.rust-lang.org/stable/src/core/array/equality.rs.html#133) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-%5BT;+N%5D) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [\[T; N\]](https://doc.rust-lang.org/stable/std/primitive.array.html) where T: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/core/portable-simd/crates/core_simd/src/vector.rs.html#964-967) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Simd%3CT,+N%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Simd](https://doc.rust-lang.org/stable/std/simd/struct.Simd.html "struct std::simd::Simd") where [LaneCount](https://doc.rust-lang.org/stable/std/simd/struct.LaneCount.html "struct std::simd::LaneCount") : [SupportedLaneCount](https://doc.rust-lang.org/stable/std/simd/trait.SupportedLaneCount.html "trait std::simd::SupportedLaneCount") , T: [SimdElement](https://doc.rust-lang.org/stable/std/simd/trait.SimdElement.html "trait std::simd::SimdElement") + [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , [Source](https://doc.rust-lang.org/stable/src/std/sync/mpmc/error.rs.html#9) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SendTimeoutError%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SendTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpmc/enum.SendTimeoutError.html "enum std::sync::mpmc::SendTimeoutError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#462) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-TrySendError%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [TrySendError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TrySendError.html "enum std::sync::mpsc::TrySendError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/io/cursor.rs.html#74) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-Cursor%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Cursor](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html "struct std::io::Cursor") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#406) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-SendError%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [SendError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SendError.html "struct std::sync::mpsc::SendError") 1.70.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/once_lock.rs.html#680) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-OnceLock%3CT%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [OnceLock](https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html "struct std::sync::OnceLock") [Source](https://doc.rust-lang.org/stable/src/core/ops/coroutine.rs.html#8) [§](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html#impl-Eq-for-CoroutineState%3CY,+R%3E) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [CoroutineState](https://doc.rust-lang.org/stable/std/ops/enum.CoroutineState.html "enum std::ops::CoroutineState") where Y: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , R: [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") , --- # RecvError in std::sync::mpsc - Rust [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#) ----------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) ::[mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html) Struct RecvError Copy item path =============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#418) pub struct RecvError; Expand description An error returned from the [`recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv "method std::sync::mpsc::Receiver::recv") function on a [`Receiver`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") . The [`recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv "method std::sync::mpsc::Receiver::recv") operation can only fail if the sending half of a [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") (or [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") ) is disconnected, implying that no further messages will ever be received. Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#trait-implementations) --------------------------------------------------------------------------------------------------------------------- 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Clone-for-RecvError) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Debug-for-RecvError) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1151-1155) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Display-for-RecvError) ### impl [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1152-1154) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.fmt-1) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html#tymethod.fmt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1158) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Error-for-RecvError) ### impl [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#111) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.source) #### fn [source](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&(dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") + 'static)> Returns the lower-level source of this error, if any. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.source) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#137) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.description) #### fn [description](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) (&self) -> &[str](https://doc.rust-lang.org/stable/std/primitive.str.html) 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.description) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#147) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.cause) #### fn [cause](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.cause) (&self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <&dyn [Error](https://doc.rust-lang.org/stable/std/error/trait.Error.html "trait std::error::Error") \> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [Source](https://doc.rust-lang.org/stable/src/core/error.rs.html#210) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.provide) #### fn [provide](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) <'a>(&'a self, request: &mut [Request](https://doc.rust-lang.org/stable/std/error/struct.Request.html "struct std::error::Request") <'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301) ) Provides type-based access to context intended for error reports. [Read more](https://doc.rust-lang.org/stable/std/error/trait.Error.html#method.provide) 1.24.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1201-1212) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-From%3CRecvError%3E-for-RecvTimeoutError) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") \> for [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1207-1211) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.from-1) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (err: [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") ) -> [RecvTimeoutError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.RecvTimeoutError.html "enum std::sync::mpsc::RecvTimeoutError") Converts a `RecvError` into a `RecvTimeoutError`. This conversion always returns `RecvTimeoutError::Disconnected`. No data is allocated on the heap. 1.24.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1174-1185) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-From%3CRecvError%3E-for-TryRecvError) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") <[RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") \> for [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1180-1184) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (err: [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") ) -> [TryRecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/enum.TryRecvError.html "enum std::sync::mpsc::TryRecvError") Converts a `RecvError` into a `TryRecvError`. This conversion always returns `TryRecvError::Disconnected`. No data is allocated on the heap. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-PartialEq-for-RecvError) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Copy-for-RecvError) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Eq-for-RecvError) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#416) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-StructuralPartialEq-for-RecvError) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Freeze-for-RecvError) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-RefUnwindSafe-for-RecvError) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Send-for-RecvError) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Sync-for-RecvError) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Unpin-for-RecvError) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-UnwindSafe-for-RecvError) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [RecvError](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html "struct std::sync::mpsc::RecvError") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.from-2) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2866) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-ToString-for-T) ### impl [ToString](https://doc.rust-lang.org/stable/std/string/trait.ToString.html "trait std::string::ToString") for T where T: [Display](https://doc.rust-lang.org/stable/std/fmt/trait.Display.html "trait std::fmt::Display") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/alloc/string.rs.html#2868) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.to_string) #### fn [to\_string](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) (&self) -> [String](https://doc.rust-lang.org/stable/std/string/struct.String.html "struct std::string::String") Converts the given value to a `String`. [Read more](https://doc.rust-lang.org/stable/std/string/trait.ToString.html#tymethod.to_string) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.RecvError.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Duration in std::time - Rust [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#) ---------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[time](https://doc.rust-lang.org/stable/std/time/index.html) Struct Duration Copy item path ============================== 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#81) pub struct Duration { /* private fields */ } Expand description A `Duration` type to represent a span of time, typically used for system timeouts. Each `Duration` is composed of a whole number of seconds and a fractional part represented in nanoseconds. If the underlying system does not support nanosecond-level precision, APIs binding a system timeout will typically round up the number of nanoseconds. [`Duration`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") s implement many common traits, including [`Add`](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") , [`Sub`](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html "trait std::ops::Sub") , and other [`ops`](https://doc.rust-lang.org/stable/std/ops/index.html "mod std::ops") traits. It implements [`Default`](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") by returning a zero-length `Duration`. [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples) Examples ------------------------------------------------------------------------------------- use std::time::Duration; let five_seconds = Duration::new(5, 0); let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5); assert_eq!(five_seconds_and_five_nanos.as_secs(), 5); assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5); let ten_millis = Duration::from_millis(10); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+five_seconds+=+Duration::new(5,+0);%0A++++let+five_seconds_and_five_nanos+=+five_seconds+%2B+Duration::new(0,+5);%0A++++%0A++++assert_eq!(five_seconds_and_five_nanos.as_secs(),+5);%0A++++assert_eq!(five_seconds_and_five_nanos.subsec_nanos(),+5);%0A++++%0A++++let+ten_millis+=+Duration::from_millis(10);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#formatting-duration-values) Formatting `Duration` values --------------------------------------------------------------------------------------------------------------------------- `Duration` intentionally does not have a `Display` impl, as there are a variety of ways to format spans of time for human readability. `Duration` provides a `Debug` impl that shows the full precision of the value. The `Debug` output uses the non-ASCII “µs” suffix for microseconds. If your program output may appear in contexts that cannot rely on full Unicode compatibility, you may wish to format `Duration` objects yourself or use a crate to do so. Implementations[§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#implementations) --------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#86) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Duration) ### impl [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#98) #### pub const [SECOND](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.SECOND) : [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_constants` [#57391](https://github.com/rust-lang/rust/issues/57391) ) The duration of one second. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-1) Examples #![feature(duration_constants)] use std::time::Duration; assert_eq!(Duration::SECOND, Duration::from_secs(1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constants)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::SECOND,+Duration::from_secs(1));%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#111) #### pub const [MILLISECOND](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.MILLISECOND) : [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_constants` [#57391](https://github.com/rust-lang/rust/issues/57391) ) The duration of one millisecond. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-2) Examples #![feature(duration_constants)] use std::time::Duration; assert_eq!(Duration::MILLISECOND, Duration::from_millis(1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constants)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::MILLISECOND,+Duration::from_millis(1));%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#124) #### pub const [MICROSECOND](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.MICROSECOND) : [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_constants` [#57391](https://github.com/rust-lang/rust/issues/57391) ) The duration of one microsecond. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-3) Examples #![feature(duration_constants)] use std::time::Duration; assert_eq!(Duration::MICROSECOND, Duration::from_micros(1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constants)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::MICROSECOND,+Duration::from_micros(1));%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#137) #### pub const [NANOSECOND](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.NANOSECOND) : [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_constants` [#57391](https://github.com/rust-lang/rust/issues/57391) ) The duration of one nanosecond. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-4) Examples #![feature(duration_constants)] use std::time::Duration; assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constants)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::NANOSECOND,+Duration::from_nanos(1));%0A%7D&version=nightly&edition=2024 "Run code") 1.53.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#151) #### pub const [ZERO](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.ZERO) : [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") A duration of zero time. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-5) Examples use std::time::Duration; let duration = Duration::ZERO; assert!(duration.is_zero()); assert_eq!(duration.as_nanos(), 0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::ZERO;%0A++++assert!(duration.is_zero());%0A++++assert_eq!(duration.as_nanos(),+0);%0A%7D&edition=2024 "Run code") 1.53.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#170) #### pub const [MAX](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.MAX) : [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") The maximum duration. May vary by platform as necessary. Must be able to contain the difference between two instances of [`Instant`](https://doc.rust-lang.org/stable/std/time/struct.Instant.html) or two instances of [`SystemTime`](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html) . This constraint gives it a value of about 584,942,417,355 years in practice, which is currently used on all platforms. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-6) Examples use std::time::Duration; assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::MAX,+Duration::new(u64::MAX,+1_000_000_000+-+1));%0A%7D&edition=2024 "Run code") 1.3.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#194) #### pub const fn [new](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.new) (secs: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) , nanos: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of whole seconds and additional nanoseconds. If the number of nanoseconds is greater than 1 billion (the number of nanoseconds in a second), then it will carry over into the seconds provided. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics) Panics This constructor will panic if the carry from the nanoseconds overflows the seconds counter. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-7) Examples use std::time::Duration; let five_seconds = Duration::new(5, 0); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+five_seconds+=+Duration::new(5,+0);%0A%7D&edition=2024 "Run code") 1.3.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#224) #### pub const fn [from\_secs](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_secs) (secs: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of whole seconds. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-8) Examples use std::time::Duration; let duration = Duration::from_secs(5); assert_eq!(5, duration.as_secs()); assert_eq!(0, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_secs(5);%0A++++%0A++++assert_eq!(5,+duration.as_secs());%0A++++assert_eq!(0,+duration.subsec_nanos());%0A%7D&edition=2024 "Run code") 1.3.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#244) #### pub const fn [from\_millis](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_millis) (millis: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of milliseconds. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-9) Examples use std::time::Duration; let duration = Duration::from_millis(2_569); assert_eq!(2, duration.as_secs()); assert_eq!(569_000_000, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_millis(2_569);%0A++++%0A++++assert_eq!(2,+duration.as_secs());%0A++++assert_eq!(569_000_000,+duration.subsec_nanos());%0A%7D&edition=2024 "Run code") 1.27.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#270) #### pub const fn [from\_micros](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_micros) (micros: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of microseconds. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-10) Examples use std::time::Duration; let duration = Duration::from_micros(1_000_002); assert_eq!(1, duration.as_secs()); assert_eq!(2_000, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_micros(1_000_002);%0A++++%0A++++assert_eq!(1,+duration.as_secs());%0A++++assert_eq!(2_000,+duration.subsec_nanos());%0A%7D&edition=2024 "Run code") 1.27.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#301) #### pub const fn [from\_nanos](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_nanos) (nanos: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of nanoseconds. Note: Using this on the return value of `as_nanos()` might cause unexpected behavior: `as_nanos()` returns a u128, and can return values that do not fit in u64, e.g. 585 years. Instead, consider using the pattern `Duration::new(d.as_secs(), d.subsec_nanos())` if you cannot copy/clone the Duration directly. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-11) Examples use std::time::Duration; let duration = Duration::from_nanos(1_000_000_123); assert_eq!(1, duration.as_secs()); assert_eq!(123, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_nanos(1_000_000_123);%0A++++%0A++++assert_eq!(1,+duration.as_secs());%0A++++assert_eq!(123,+duration.subsec_nanos());%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#335) #### pub const fn [from\_nanos\_u128](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_nanos_u128) (nanos: [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_from_nanos_u128` [#139201](https://github.com/rust-lang/rust/issues/139201) ) Creates a new `Duration` from the specified number of nanoseconds. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-1) Panics Panics if the given number of nanoseconds is greater than [`Duration::MAX`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.MAX "associated constant std::time::Duration::MAX") . ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-12) Examples #![feature(duration_from_nanos_u128)] use std::time::Duration; let nanos = 10_u128.pow(24) + 321; let duration = Duration::from_nanos_u128(nanos); assert_eq!(10_u64.pow(15), duration.as_secs()); assert_eq!(321, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_from_nanos_u128)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+nanos+=+10_u128.pow(24)+%2B+321;%0A++++let+duration+=+Duration::from_nanos_u128(nanos);%0A++++%0A++++assert_eq!(10_u64.pow(15),+duration.as_secs());%0A++++assert_eq!(321,+duration.subsec_nanos());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#367) #### pub const fn [from\_weeks](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_weeks) (weeks: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_constructors` [#120301](https://github.com/rust-lang/rust/issues/120301) ) Creates a new `Duration` from the specified number of weeks. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-2) Panics Panics if the given number of weeks overflows the `Duration` size. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-13) Examples #![feature(duration_constructors)] use std::time::Duration; let duration = Duration::from_weeks(4); assert_eq!(4 * 7 * 24 * 60 * 60, duration.as_secs()); assert_eq!(0, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constructors)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_weeks(4);%0A++++%0A++++assert_eq!(4+*+7+*+24+*+60+*+60,+duration.as_secs());%0A++++assert_eq!(0,+duration.subsec_nanos());%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#395) #### pub const fn [from\_days](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_days) (days: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 🔬This is a nightly-only experimental API. (`duration_constructors` [#120301](https://github.com/rust-lang/rust/issues/120301) ) Creates a new `Duration` from the specified number of days. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-3) Panics Panics if the given number of days overflows the `Duration` size. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-14) Examples #![feature(duration_constructors)] use std::time::Duration; let duration = Duration::from_days(7); assert_eq!(7 * 24 * 60 * 60, duration.as_secs()); assert_eq!(0, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constructors)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_days(7);%0A++++%0A++++assert_eq!(7+*+24+*+60+*+60,+duration.as_secs());%0A++++assert_eq!(0,+duration.subsec_nanos());%0A%7D&version=nightly&edition=2024 "Run code") 1.91.0 (const: 1.91.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#423) #### pub const fn [from\_hours](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_hours) (hours: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of hours. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-4) Panics Panics if the given number of hours overflows the `Duration` size. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-15) Examples use std::time::Duration; let duration = Duration::from_hours(6); assert_eq!(6 * 60 * 60, duration.as_secs()); assert_eq!(0, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_hours(6);%0A++++%0A++++assert_eq!(6+*+60+*+60,+duration.as_secs());%0A++++assert_eq!(0,+duration.subsec_nanos());%0A%7D&edition=2024 "Run code") 1.91.0 (const: 1.91.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#451) #### pub const fn [from\_mins](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_mins) (mins: [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of minutes. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-5) Panics Panics if the given number of minutes overflows the `Duration` size. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-16) Examples use std::time::Duration; let duration = Duration::from_mins(10); assert_eq!(10 * 60, duration.as_secs()); assert_eq!(0, duration.subsec_nanos()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_mins(10);%0A++++%0A++++assert_eq!(10+*+60,+duration.as_secs());%0A++++assert_eq!(0,+duration.subsec_nanos());%0A%7D&edition=2024 "Run code") 1.53.0 (const: 1.53.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#479) #### pub const fn [is\_zero](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.is_zero) (&self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Returns true if this `Duration` spans no time. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-17) Examples use std::time::Duration; assert!(Duration::ZERO.is_zero()); assert!(Duration::new(0, 0).is_zero()); assert!(Duration::from_nanos(0).is_zero()); assert!(Duration::from_secs(0).is_zero()); assert!(!Duration::new(1, 1).is_zero()); assert!(!Duration::from_nanos(1).is_zero()); assert!(!Duration::from_secs(1).is_zero()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert!(Duration::ZERO.is_zero());%0A++++assert!(Duration::new(0,+0).is_zero());%0A++++assert!(Duration::from_nanos(0).is_zero());%0A++++assert!(Duration::from_secs(0).is_zero());%0A++++%0A++++assert!(!Duration::new(1,+1).is_zero());%0A++++assert!(!Duration::from_nanos(1).is_zero());%0A++++assert!(!Duration::from_secs(1).is_zero());%0A%7D&edition=2024 "Run code") 1.3.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#507) #### pub const fn [as\_secs](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_secs) (&self) -> [u64](https://doc.rust-lang.org/stable/std/primitive.u64.html) Returns the number of _whole_ seconds contained by this `Duration`. The returned value does not include the fractional (nanosecond) part of the duration, which can be obtained using [`subsec_nanos`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.subsec_nanos "method std::time::Duration::subsec_nanos") . ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-18) Examples use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_secs(), 5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::new(5,+730_023_852);%0A++++assert_eq!(duration.as_secs(),+5);%0A%7D&edition=2024 "Run code") To determine the total number of seconds represented by the `Duration` including the fractional part, use [`as_secs_f64`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_secs_f64 "method std::time::Duration::as_secs_f64") or [`as_secs_f32`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_secs_f32 "method std::time::Duration::as_secs_f32") 1.27.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#530) #### pub const fn [subsec\_millis](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.subsec_millis) (&self) -> [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) Returns the fractional part of this `Duration`, in whole milliseconds. This method does **not** return the length of the duration when represented by milliseconds. The returned number always represents a fractional portion of a second (i.e., it is less than one thousand). ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-19) Examples use std::time::Duration; let duration = Duration::from_millis(5_432); assert_eq!(duration.as_secs(), 5); assert_eq!(duration.subsec_millis(), 432); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_millis(5_432);%0A++++assert_eq!(duration.as_secs(),+5);%0A++++assert_eq!(duration.subsec_millis(),+432);%0A%7D&edition=2024 "Run code") 1.27.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#553) #### pub const fn [subsec\_micros](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.subsec_micros) (&self) -> [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) Returns the fractional part of this `Duration`, in whole microseconds. This method does **not** return the length of the duration when represented by microseconds. The returned number always represents a fractional portion of a second (i.e., it is less than one million). ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-20) Examples use std::time::Duration; let duration = Duration::from_micros(1_234_567); assert_eq!(duration.as_secs(), 1); assert_eq!(duration.subsec_micros(), 234_567); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_micros(1_234_567);%0A++++assert_eq!(duration.as_secs(),+1);%0A++++assert_eq!(duration.subsec_micros(),+234_567);%0A%7D&edition=2024 "Run code") 1.3.0 (const: 1.32.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#576) #### pub const fn [subsec\_nanos](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.subsec_nanos) (&self) -> [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) Returns the fractional part of this `Duration`, in nanoseconds. This method does **not** return the length of the duration when represented by nanoseconds. The returned number always represents a fractional portion of a second (i.e., it is less than one billion). ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-21) Examples use std::time::Duration; let duration = Duration::from_millis(5_010); assert_eq!(duration.as_secs(), 5); assert_eq!(duration.subsec_nanos(), 10_000_000); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::from_millis(5_010);%0A++++assert_eq!(duration.as_secs(),+5);%0A++++assert_eq!(duration.subsec_nanos(),+10_000_000);%0A%7D&edition=2024 "Run code") 1.33.0 (const: 1.33.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#594) #### pub const fn [as\_millis](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_millis) (&self) -> [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) Returns the total number of whole milliseconds contained by this `Duration`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-22) Examples use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_millis(), 5_730); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::new(5,+730_023_852);%0A++++assert_eq!(duration.as_millis(),+5_730);%0A%7D&edition=2024 "Run code") 1.33.0 (const: 1.33.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#613) #### pub const fn [as\_micros](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_micros) (&self) -> [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) Returns the total number of whole microseconds contained by this `Duration`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-23) Examples use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_micros(), 5_730_023); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::new(5,+730_023_852);%0A++++assert_eq!(duration.as_micros(),+5_730_023);%0A%7D&edition=2024 "Run code") 1.33.0 (const: 1.33.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#632) #### pub const fn [as\_nanos](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_nanos) (&self) -> [u128](https://doc.rust-lang.org/stable/std/primitive.u128.html) Returns the total number of nanoseconds contained by this `Duration`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-24) Examples use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_nanos(), 5_730_023_852); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+duration+=+Duration::new(5,+730_023_852);%0A++++assert_eq!(duration.as_nanos(),+5_730_023_852);%0A%7D&edition=2024 "Run code") 1.81.0 (const: 1.81.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#651) #### pub const fn [abs\_diff](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.abs_diff) (self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Computes the absolute difference between `self` and `other`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-25) Examples use std::time::Duration; assert_eq!(Duration::new(100, 0).abs_diff(Duration::new(80, 0)), Duration::new(20, 0)); assert_eq!(Duration::new(100, 400_000_000).abs_diff(Duration::new(110, 0)), Duration::new(9, 600_000_000)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(100,+0).abs_diff(Duration::new(80,+0)),+Duration::new(20,+0));%0A++++assert_eq!(Duration::new(100,+400_000_000).abs_diff(Duration::new(110,+0)),+Duration::new(9,+600_000_000));%0A%7D&edition=2024 "Run code") 1.16.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#671) #### pub const fn [checked\_add](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.checked_add) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> Checked `Duration` addition. Computes `self + other`, returning [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if overflow occurred. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-26) Examples use std::time::Duration; assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1))); assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(0,+0).checked_add(Duration::new(0,+1)),+Some(Duration::new(0,+1)));%0A++++assert_eq!(Duration::new(1,+0).checked_add(Duration::new(u64::MAX,+0)),+None);%0A%7D&edition=2024 "Run code") 1.53.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#706) #### pub const fn [saturating\_add](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.saturating_add) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.MAX "associated constant std::time::Duration::MAX") if overflow occurred. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-27) Examples #![feature(duration_constants)] use std::time::Duration; assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1)); assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constants)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(0,+0).saturating_add(Duration::new(0,+1)),+Duration::new(0,+1));%0A++++assert_eq!(Duration::new(1,+0).saturating_add(Duration::new(u64::MAX,+0)),+Duration::MAX);%0A%7D&version=nightly&edition=2024 "Run code") 1.16.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#729) #### pub const fn [checked\_sub](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.checked_sub) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> Checked `Duration` subtraction. Computes `self - other`, returning [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if the result would be negative or if overflow occurred. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-28) Examples use std::time::Duration; assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1))); assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(0,+1).checked_sub(Duration::new(0,+0)),+Some(Duration::new(0,+1)));%0A++++assert_eq!(Duration::new(0,+0).checked_sub(Duration::new(0,+1)),+None);%0A%7D&edition=2024 "Run code") 1.53.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#762) #### pub const fn [saturating\_sub](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.saturating_sub) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.ZERO "associated constant std::time::Duration::ZERO") if the result would be negative or if overflow occurred. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-29) Examples use std::time::Duration; assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1)); assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(0,+1).saturating_sub(Duration::new(0,+0)),+Duration::new(0,+1));%0A++++assert_eq!(Duration::new(0,+0).saturating_sub(Duration::new(0,+1)),+Duration::ZERO);%0A%7D&edition=2024 "Run code") 1.16.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#785) #### pub const fn [checked\_mul](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.checked_mul) (self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> Checked `Duration` multiplication. Computes `self * other`, returning [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if overflow occurred. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-30) Examples use std::time::Duration; assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2))); assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(0,+500_000_001).checked_mul(2),+Some(Duration::new(1,+2)));%0A++++assert_eq!(Duration::new(u64::MAX+-+1,+0).checked_mul(2),+None);%0A%7D&edition=2024 "Run code") 1.53.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#817) #### pub const fn [saturating\_mul](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.saturating_mul) (self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Saturating `Duration` multiplication. Computes `self * other`, returning [`Duration::MAX`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedconstant.MAX "associated constant std::time::Duration::MAX") if overflow occurred. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-31) Examples #![feature(duration_constants)] use std::time::Duration; assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2)); assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_constants)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(0,+500_000_001).saturating_mul(2),+Duration::new(1,+2));%0A++++assert_eq!(Duration::new(u64::MAX+-+1,+0).saturating_mul(2),+Duration::MAX);%0A%7D&version=nightly&edition=2024 "Run code") 1.16.0 (const: 1.58.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#841) #### pub const fn [checked\_div](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.checked_div) (self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> Checked `Duration` division. Computes `self / other`, returning [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") if `other == 0`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-32) Examples use std::time::Duration; assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0))); assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000))); assert_eq!(Duration::new(2, 0).checked_div(0), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++assert_eq!(Duration::new(2,+0).checked_div(2),+Some(Duration::new(1,+0)));%0A++++assert_eq!(Duration::new(1,+0).checked_div(2),+Some(Duration::new(0,+500_000_000)));%0A++++assert_eq!(Duration::new(2,+0).checked_div(0),+None);%0A%7D&edition=2024 "Run code") 1.38.0 (const: 1.83.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#870) #### pub const fn [as\_secs\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_secs_f64) (&self) -> [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) Returns the number of seconds contained by this `Duration` as `f64`. The returned value includes the fractional (nanosecond) part of the duration. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-33) Examples use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.as_secs_f64(), 2.7); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+700_000_000);%0A++++assert_eq!(dur.as_secs_f64(),+2.7);%0A%7D&edition=2024 "Run code") 1.38.0 (const: 1.83.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#889) #### pub const fn [as\_secs\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_secs_f32) (&self) -> [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) Returns the number of seconds contained by this `Duration` as `f32`. The returned value includes the fractional (nanosecond) part of the duration. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-34) Examples use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.as_secs_f32(), 2.7); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+700_000_000);%0A++++assert_eq!(dur.as_secs_f32(),+2.7);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#908) #### pub const fn [as\_millis\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_millis_f64) (&self) -> [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) 🔬This is a nightly-only experimental API. (`duration_millis_float` [#122451](https://github.com/rust-lang/rust/issues/122451) ) Returns the number of milliseconds contained by this `Duration` as `f64`. The returned value includes the fractional (nanosecond) part of the duration. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-35) Examples #![feature(duration_millis_float)] use std::time::Duration; let dur = Duration::new(2, 345_678_000); assert_eq!(dur.as_millis_f64(), 2_345.678); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_millis_float)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+345_678_000);%0A++++assert_eq!(dur.as_millis_f64(),+2_345.678);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#928) #### pub const fn [as\_millis\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.as_millis_f32) (&self) -> [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) 🔬This is a nightly-only experimental API. (`duration_millis_float` [#122451](https://github.com/rust-lang/rust/issues/122451) ) Returns the number of milliseconds contained by this `Duration` as `f32`. The returned value includes the fractional (nanosecond) part of the duration. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-36) Examples #![feature(duration_millis_float)] use std::time::Duration; let dur = Duration::new(2, 345_678_000); assert_eq!(dur.as_millis_f32(), 2_345.678); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(duration_millis_float)%5D%0A%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+345_678_000);%0A++++assert_eq!(dur.as_millis_f32(),+2_345.678);%0A%7D&version=nightly&edition=2024 "Run code") 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#963) #### pub fn [from\_secs\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_secs_f64) (secs: [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of seconds represented as `f64`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-6) Panics This constructor will panic if `secs` is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-37) Examples use std::time::Duration; let res = Duration::from_secs_f64(0.0); assert_eq!(res, Duration::new(0, 0)); let res = Duration::from_secs_f64(1e-20); assert_eq!(res, Duration::new(0, 0)); let res = Duration::from_secs_f64(4.2e-7); assert_eq!(res, Duration::new(0, 420)); let res = Duration::from_secs_f64(2.7); assert_eq!(res, Duration::new(2, 700_000_000)); let res = Duration::from_secs_f64(3e10); assert_eq!(res, Duration::new(30_000_000_000, 0)); // subnormal float let res = Duration::from_secs_f64(f64::from_bits(1)); assert_eq!(res, Duration::new(0, 0)); // conversion uses rounding let res = Duration::from_secs_f64(0.999e-9); assert_eq!(res, Duration::new(0, 1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+res+=+Duration::from_secs_f64(0.0);%0A++++assert_eq!(res,+Duration::new(0,+0));%0A++++let+res+=+Duration::from_secs_f64(1e-20);%0A++++assert_eq!(res,+Duration::new(0,+0));%0A++++let+res+=+Duration::from_secs_f64(4.2e-7);%0A++++assert_eq!(res,+Duration::new(0,+420));%0A++++let+res+=+Duration::from_secs_f64(2.7);%0A++++assert_eq!(res,+Duration::new(2,+700_000_000));%0A++++let+res+=+Duration::from_secs_f64(3e10);%0A++++assert_eq!(res,+Duration::new(30_000_000_000,+0));%0A++++//+subnormal+float%0A++++let+res+=+Duration::from_secs_f64(f64::from_bits(1));%0A++++assert_eq!(res,+Duration::new(0,+0));%0A++++//+conversion+uses+rounding%0A++++let+res+=+Duration::from_secs_f64(0.999e-9);%0A++++assert_eq!(res,+Duration::new(0,+1));%0A%7D&edition=2024 "Run code") 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1000) #### pub fn [from\_secs\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_secs_f32) (secs: [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Creates a new `Duration` from the specified number of seconds represented as `f32`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-7) Panics This constructor will panic if `secs` is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-38) Examples use std::time::Duration; let res = Duration::from_secs_f32(0.0); assert_eq!(res, Duration::new(0, 0)); let res = Duration::from_secs_f32(1e-20); assert_eq!(res, Duration::new(0, 0)); let res = Duration::from_secs_f32(4.2e-7); assert_eq!(res, Duration::new(0, 420)); let res = Duration::from_secs_f32(2.7); assert_eq!(res, Duration::new(2, 700_000_048)); let res = Duration::from_secs_f32(3e10); assert_eq!(res, Duration::new(30_000_001_024, 0)); // subnormal float let res = Duration::from_secs_f32(f32::from_bits(1)); assert_eq!(res, Duration::new(0, 0)); // conversion uses rounding let res = Duration::from_secs_f32(0.999e-9); assert_eq!(res, Duration::new(0, 1)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+res+=+Duration::from_secs_f32(0.0);%0A++++assert_eq!(res,+Duration::new(0,+0));%0A++++let+res+=+Duration::from_secs_f32(1e-20);%0A++++assert_eq!(res,+Duration::new(0,+0));%0A++++let+res+=+Duration::from_secs_f32(4.2e-7);%0A++++assert_eq!(res,+Duration::new(0,+420));%0A++++let+res+=+Duration::from_secs_f32(2.7);%0A++++assert_eq!(res,+Duration::new(2,+700_000_048));%0A++++let+res+=+Duration::from_secs_f32(3e10);%0A++++assert_eq!(res,+Duration::new(30_000_001_024,+0));%0A++++//+subnormal+float%0A++++let+res+=+Duration::from_secs_f32(f32::from_bits(1));%0A++++assert_eq!(res,+Duration::new(0,+0));%0A++++//+conversion+uses+rounding%0A++++let+res+=+Duration::from_secs_f32(0.999e-9);%0A++++assert_eq!(res,+Duration::new(0,+1));%0A%7D&edition=2024 "Run code") 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1024) #### pub fn [mul\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.mul_f64) (self, rhs: [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Multiplies `Duration` by `f64`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-8) Panics This method will panic if result is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-39) Examples use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000)); assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+700_000_000);%0A++++assert_eq!(dur.mul_f64(3.14),+Duration::new(8,+478_000_000));%0A++++assert_eq!(dur.mul_f64(3.14e5),+Duration::new(847_800,+0));%0A%7D&edition=2024 "Run code") 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1045) #### pub fn [mul\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.mul_f32) (self, rhs: [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Multiplies `Duration` by `f32`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-9) Panics This method will panic if result is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-40) Examples use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_641)); assert_eq!(dur.mul_f32(3.14e5), Duration::new(847_800, 0)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+700_000_000);%0A++++assert_eq!(dur.mul_f32(3.14),+Duration::new(8,+478_000_641));%0A++++assert_eq!(dur.mul_f32(3.14e5),+Duration::new(847_800,+0));%0A%7D&edition=2024 "Run code") 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1066) #### pub fn [div\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.div_f64) (self, rhs: [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Divides `Duration` by `f64`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-10) Panics This method will panic if result is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-41) Examples use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611)); assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_599)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+700_000_000);%0A++++assert_eq!(dur.div_f64(3.14),+Duration::new(0,+859_872_611));%0A++++assert_eq!(dur.div_f64(3.14e5),+Duration::new(0,+8_599));%0A%7D&edition=2024 "Run code") 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1089) #### pub fn [div\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.div_f32) (self, rhs: [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Divides `Duration` by `f32`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-11) Panics This method will panic if result is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-42) Examples use std::time::Duration; let dur = Duration::new(2, 700_000_000); // note that due to rounding errors result is slightly // different from 0.859_872_611 assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_580)); assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_599)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur+=+Duration::new(2,+700_000_000);%0A++++//+note+that+due+to+rounding+errors+result+is+slightly%0A++++//+different+from+0.859_872_611%0A++++assert_eq!(dur.div_f32(3.14),+Duration::new(0,+859_872_580));%0A++++assert_eq!(dur.div_f32(3.14e5),+Duration::new(0,+8_599));%0A%7D&edition=2024 "Run code") 1.80.0 (const: 1.83.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1108) #### pub const fn [div\_duration\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.div_duration_f64) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) Divides `Duration` by `Duration` and returns `f64`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-43) Examples use std::time::Duration; let dur1 = Duration::new(2, 700_000_000); let dur2 = Duration::new(5, 400_000_000); assert_eq!(dur1.div_duration_f64(dur2), 0.5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur1+=+Duration::new(2,+700_000_000);%0A++++let+dur2+=+Duration::new(5,+400_000_000);%0A++++assert_eq!(dur1.div_duration_f64(dur2),+0.5);%0A%7D&edition=2024 "Run code") 1.80.0 (const: 1.83.0) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1130) #### pub const fn [div\_duration\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.div_duration_f32) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) Divides `Duration` by `Duration` and returns `f32`. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-44) Examples use std::time::Duration; let dur1 = Duration::new(2, 700_000_000); let dur2 = Duration::new(5, 400_000_000); assert_eq!(dur1.div_duration_f32(dur2), 0.5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+dur1+=+Duration::new(2,+700_000_000);%0A++++let+dur2+=+Duration::new(5,+400_000_000);%0A++++assert_eq!(dur1.div_duration_f32(dur2),+0.5);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1587) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Duration-1) ### impl [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 1.66.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1645) #### pub fn [try\_from\_secs\_f32](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.try_from_secs_f32) (secs: [f32](https://doc.rust-lang.org/stable/std/primitive.f32.html) ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") , [TryFromFloatSecsError](https://doc.rust-lang.org/stable/std/time/struct.TryFromFloatSecsError.html "struct std::time::TryFromFloatSecsError") \> The checked version of [`from_secs_f32`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_secs_f32 "associated function std::time::Duration::from_secs_f32") . This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-45) Examples use std::time::Duration; let res = Duration::try_from_secs_f32(0.0); assert_eq!(res, Ok(Duration::new(0, 0))); let res = Duration::try_from_secs_f32(1e-20); assert_eq!(res, Ok(Duration::new(0, 0))); let res = Duration::try_from_secs_f32(4.2e-7); assert_eq!(res, Ok(Duration::new(0, 420))); let res = Duration::try_from_secs_f32(2.7); assert_eq!(res, Ok(Duration::new(2, 700_000_048))); let res = Duration::try_from_secs_f32(3e10); assert_eq!(res, Ok(Duration::new(30_000_001_024, 0))); // subnormal float: let res = Duration::try_from_secs_f32(f32::from_bits(1)); assert_eq!(res, Ok(Duration::new(0, 0))); let res = Duration::try_from_secs_f32(-5.0); assert!(res.is_err()); let res = Duration::try_from_secs_f32(f32::NAN); assert!(res.is_err()); let res = Duration::try_from_secs_f32(2e19); assert!(res.is_err()); // the conversion uses rounding with tie resolution to even let res = Duration::try_from_secs_f32(0.999e-9); assert_eq!(res, Ok(Duration::new(0, 1))); // this float represents exactly 976562.5e-9 let val = f32::from_bits(0x3A80_0000); let res = Duration::try_from_secs_f32(val); assert_eq!(res, Ok(Duration::new(0, 976_562))); // this float represents exactly 2929687.5e-9 let val = f32::from_bits(0x3B40_0000); let res = Duration::try_from_secs_f32(val); assert_eq!(res, Ok(Duration::new(0, 2_929_688))); // this float represents exactly 1.000_976_562_5 let val = f32::from_bits(0x3F802000); let res = Duration::try_from_secs_f32(val); assert_eq!(res, Ok(Duration::new(1, 976_562))); // this float represents exactly 1.002_929_687_5 let val = f32::from_bits(0x3F806000); let res = Duration::try_from_secs_f32(val); assert_eq!(res, Ok(Duration::new(1, 2_929_688))); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+res+=+Duration::try_from_secs_f32(0.0);%0A++++assert_eq!(res,+Ok(Duration::new(0,+0)));%0A++++let+res+=+Duration::try_from_secs_f32(1e-20);%0A++++assert_eq!(res,+Ok(Duration::new(0,+0)));%0A++++let+res+=+Duration::try_from_secs_f32(4.2e-7);%0A++++assert_eq!(res,+Ok(Duration::new(0,+420)));%0A++++let+res+=+Duration::try_from_secs_f32(2.7);%0A++++assert_eq!(res,+Ok(Duration::new(2,+700_000_048)));%0A++++let+res+=+Duration::try_from_secs_f32(3e10);%0A++++assert_eq!(res,+Ok(Duration::new(30_000_001_024,+0)));%0A++++//+subnormal+float:%0A++++let+res+=+Duration::try_from_secs_f32(f32::from_bits(1));%0A++++assert_eq!(res,+Ok(Duration::new(0,+0)));%0A++++%0A++++let+res+=+Duration::try_from_secs_f32(-5.0);%0A++++assert!(res.is_err());%0A++++let+res+=+Duration::try_from_secs_f32(f32::NAN);%0A++++assert!(res.is_err());%0A++++let+res+=+Duration::try_from_secs_f32(2e19);%0A++++assert!(res.is_err());%0A++++%0A++++//+the+conversion+uses+rounding+with+tie+resolution+to+even%0A++++let+res+=+Duration::try_from_secs_f32(0.999e-9);%0A++++assert_eq!(res,+Ok(Duration::new(0,+1)));%0A++++%0A++++//+this+float+represents+exactly+976562.5e-9%0A++++let+val+=+f32::from_bits(0x3A80_0000);%0A++++let+res+=+Duration::try_from_secs_f32(val);%0A++++assert_eq!(res,+Ok(Duration::new(0,+976_562)));%0A++++%0A++++//+this+float+represents+exactly+2929687.5e-9%0A++++let+val+=+f32::from_bits(0x3B40_0000);%0A++++let+res+=+Duration::try_from_secs_f32(val);%0A++++assert_eq!(res,+Ok(Duration::new(0,+2_929_688)));%0A++++%0A++++//+this+float+represents+exactly+1.000_976_562_5%0A++++let+val+=+f32::from_bits(0x3F802000);%0A++++let+res+=+Duration::try_from_secs_f32(val);%0A++++assert_eq!(res,+Ok(Duration::new(1,+976_562)));%0A++++%0A++++//+this+float+represents+exactly+1.002_929_687_5%0A++++let+val+=+f32::from_bits(0x3F806000);%0A++++let+res+=+Duration::try_from_secs_f32(val);%0A++++assert_eq!(res,+Ok(Duration::new(1,+2_929_688)));%0A%7D&edition=2024 "Run code") 1.66.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1721) #### pub fn [try\_from\_secs\_f64](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.try_from_secs_f64) (secs: [f64](https://doc.rust-lang.org/stable/std/primitive.f64.html) ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") , [TryFromFloatSecsError](https://doc.rust-lang.org/stable/std/time/struct.TryFromFloatSecsError.html "struct std::time::TryFromFloatSecsError") \> The checked version of [`from_secs_f64`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_secs_f64 "associated function std::time::Duration::from_secs_f64") . This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite. ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#examples-46) Examples use std::time::Duration; let res = Duration::try_from_secs_f64(0.0); assert_eq!(res, Ok(Duration::new(0, 0))); let res = Duration::try_from_secs_f64(1e-20); assert_eq!(res, Ok(Duration::new(0, 0))); let res = Duration::try_from_secs_f64(4.2e-7); assert_eq!(res, Ok(Duration::new(0, 420))); let res = Duration::try_from_secs_f64(2.7); assert_eq!(res, Ok(Duration::new(2, 700_000_000))); let res = Duration::try_from_secs_f64(3e10); assert_eq!(res, Ok(Duration::new(30_000_000_000, 0))); // subnormal float let res = Duration::try_from_secs_f64(f64::from_bits(1)); assert_eq!(res, Ok(Duration::new(0, 0))); let res = Duration::try_from_secs_f64(-5.0); assert!(res.is_err()); let res = Duration::try_from_secs_f64(f64::NAN); assert!(res.is_err()); let res = Duration::try_from_secs_f64(2e19); assert!(res.is_err()); // the conversion uses rounding with tie resolution to even let res = Duration::try_from_secs_f64(0.999e-9); assert_eq!(res, Ok(Duration::new(0, 1))); let res = Duration::try_from_secs_f64(0.999_999_999_499); assert_eq!(res, Ok(Duration::new(0, 999_999_999))); let res = Duration::try_from_secs_f64(0.999_999_999_501); assert_eq!(res, Ok(Duration::new(1, 0))); let res = Duration::try_from_secs_f64(42.999_999_999_499); assert_eq!(res, Ok(Duration::new(42, 999_999_999))); let res = Duration::try_from_secs_f64(42.999_999_999_501); assert_eq!(res, Ok(Duration::new(43, 0))); // this float represents exactly 976562.5e-9 let val = f64::from_bits(0x3F50_0000_0000_0000); let res = Duration::try_from_secs_f64(val); assert_eq!(res, Ok(Duration::new(0, 976_562))); // this float represents exactly 2929687.5e-9 let val = f64::from_bits(0x3F68_0000_0000_0000); let res = Duration::try_from_secs_f64(val); assert_eq!(res, Ok(Duration::new(0, 2_929_688))); // this float represents exactly 1.000_976_562_5 let val = f64::from_bits(0x3FF0_0400_0000_0000); let res = Duration::try_from_secs_f64(val); assert_eq!(res, Ok(Duration::new(1, 976_562))); // this float represents exactly 1.002_929_687_5 let val = f64::from_bits(0x3_FF00_C000_0000_000); let res = Duration::try_from_secs_f64(val); assert_eq!(res, Ok(Duration::new(1, 2_929_688))); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::time::Duration;%0A++++%0A++++let+res+=+Duration::try_from_secs_f64(0.0);%0A++++assert_eq!(res,+Ok(Duration::new(0,+0)));%0A++++let+res+=+Duration::try_from_secs_f64(1e-20);%0A++++assert_eq!(res,+Ok(Duration::new(0,+0)));%0A++++let+res+=+Duration::try_from_secs_f64(4.2e-7);%0A++++assert_eq!(res,+Ok(Duration::new(0,+420)));%0A++++let+res+=+Duration::try_from_secs_f64(2.7);%0A++++assert_eq!(res,+Ok(Duration::new(2,+700_000_000)));%0A++++let+res+=+Duration::try_from_secs_f64(3e10);%0A++++assert_eq!(res,+Ok(Duration::new(30_000_000_000,+0)));%0A++++//+subnormal+float%0A++++let+res+=+Duration::try_from_secs_f64(f64::from_bits(1));%0A++++assert_eq!(res,+Ok(Duration::new(0,+0)));%0A++++%0A++++let+res+=+Duration::try_from_secs_f64(-5.0);%0A++++assert!(res.is_err());%0A++++let+res+=+Duration::try_from_secs_f64(f64::NAN);%0A++++assert!(res.is_err());%0A++++let+res+=+Duration::try_from_secs_f64(2e19);%0A++++assert!(res.is_err());%0A++++%0A++++//+the+conversion+uses+rounding+with+tie+resolution+to+even%0A++++let+res+=+Duration::try_from_secs_f64(0.999e-9);%0A++++assert_eq!(res,+Ok(Duration::new(0,+1)));%0A++++let+res+=+Duration::try_from_secs_f64(0.999_999_999_499);%0A++++assert_eq!(res,+Ok(Duration::new(0,+999_999_999)));%0A++++let+res+=+Duration::try_from_secs_f64(0.999_999_999_501);%0A++++assert_eq!(res,+Ok(Duration::new(1,+0)));%0A++++let+res+=+Duration::try_from_secs_f64(42.999_999_999_499);%0A++++assert_eq!(res,+Ok(Duration::new(42,+999_999_999)));%0A++++let+res+=+Duration::try_from_secs_f64(42.999_999_999_501);%0A++++assert_eq!(res,+Ok(Duration::new(43,+0)));%0A++++%0A++++//+this+float+represents+exactly+976562.5e-9%0A++++let+val+=+f64::from_bits(0x3F50_0000_0000_0000);%0A++++let+res+=+Duration::try_from_secs_f64(val);%0A++++assert_eq!(res,+Ok(Duration::new(0,+976_562)));%0A++++%0A++++//+this+float+represents+exactly+2929687.5e-9%0A++++let+val+=+f64::from_bits(0x3F68_0000_0000_0000);%0A++++let+res+=+Duration::try_from_secs_f64(val);%0A++++assert_eq!(res,+Ok(Duration::new(0,+2_929_688)));%0A++++%0A++++//+this+float+represents+exactly+1.000_976_562_5%0A++++let+val+=+f64::from_bits(0x3FF0_0400_0000_0000);%0A++++let+res+=+Duration::try_from_secs_f64(val);%0A++++assert_eq!(res,+Ok(Duration::new(1,+976_562)));%0A++++%0A++++//+this+float+represents+exactly+1.002_929_687_5%0A++++let+val+=+f64::from_bits(0x3_FF00_C000_0000_000);%0A++++let+res+=+Duration::try_from_secs_f64(val);%0A++++assert_eq!(res,+Ok(Duration::new(1,+2_929_688)));%0A%7D&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#trait-implementations) --------------------------------------------------------------------------------------------------------------- 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#422-432) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Add%3CDuration%3E-for-Instant) ### impl [Add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#429-431) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.add-1) #### fn [add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#tymethod.add) (self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-12) Panics This function may panic if the resulting point in time cannot be represented by the underlying data structure. See [`Instant::checked_add`](https://doc.rust-lang.org/stable/std/time/struct.Instant.html#method.checked_add "method std::time::Instant::checked_add") for a version without panic. [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#423) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-5) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#associatedtype.Output) = [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") The resulting type after applying the `+` operator. 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#606-616) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Add%3CDuration%3E-for-SystemTime) ### impl [Add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#613-615) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.add-2) #### fn [add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#tymethod.add) (self, dur: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") ##### [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#panics-13) Panics This function may panic if the resulting point in time cannot be represented by the underlying data structure. See [`SystemTime::checked_add`](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html#method.checked_add "method std::time::SystemTime::checked_add") for a version without panic. [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#607) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-7) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#associatedtype.Output) = [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") The resulting type after applying the `+` operator. 1.3.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1140) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Add-for-Duration) ### impl [Add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1141) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-1) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#associatedtype.Output) = [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") The resulting type after applying the `+` operator. [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1144) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.add) #### fn [add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#tymethod.add) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Performs the `+` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Add.html#tymethod.add) 1.9.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#435-439) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-AddAssign%3CDuration%3E-for-Instant) ### impl [AddAssign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html "trait std::ops::AddAssign") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#436-438) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.add_assign-1) #### fn [add\_assign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html#tymethod.add_assign) (&mut self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) Performs the `+=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html#tymethod.add_assign) 1.9.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#619-623) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-AddAssign%3CDuration%3E-for-SystemTime) ### impl [AddAssign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html "trait std::ops::AddAssign") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#620-622) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.add_assign-2) #### fn [add\_assign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html#tymethod.add_assign) (&mut self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) Performs the `+=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html#tymethod.add_assign) 1.9.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1151) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-AddAssign-for-Duration) ### impl [AddAssign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html "trait std::ops::AddAssign") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1153) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.add_assign) #### fn [add\_assign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html#tymethod.add_assign) (&mut self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) Performs the `+=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html#tymethod.add_assign) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Clone-for-Duration) ### impl [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1272) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Debug-for-Duration) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1273) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Default-for-Duration) ### impl [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.default) #### fn [default](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default) () -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Returns the “default value” for a type. [Read more](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default) 1.3.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1211) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Div%3Cu32%3E-for-Duration) ### impl [Div](https://doc.rust-lang.org/stable/std/ops/trait.Div.html "trait std::ops::Div") <[u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) \> for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1212) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Div.html#associatedtype.Output) = [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") The resulting type after applying the `/` operator. [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1216) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.div) #### fn [div](https://doc.rust-lang.org/stable/std/ops/trait.Div.html#tymethod.div) (self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Performs the `/` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Div.html#tymethod.div) 1.9.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1223) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-DivAssign%3Cu32%3E-for-Duration) ### impl [DivAssign](https://doc.rust-lang.org/stable/std/ops/trait.DivAssign.html "trait std::ops::DivAssign") <[u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) \> for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1226) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.div_assign) #### fn [div\_assign](https://doc.rust-lang.org/stable/std/ops/trait.DivAssign.html#tymethod.div_assign) (&mut self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) Performs the `/=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.DivAssign.html#tymethod.div_assign) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Hash-for-Duration) ### impl [Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html "trait std::hash::Hash") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.hash) #### fn [hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) <\_\_H>(&self, state: [&mut \_\_H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where \_\_H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Feeds this value into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#tymethod.hash) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#235-237) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.hash_slice) #### fn [hash\_slice](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) (data: &\[Self\], state: [&mut H](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) where H: [Hasher](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Feeds a slice of this type into the given [`Hasher`](https://doc.rust-lang.org/stable/std/hash/trait.Hasher.html "trait std::hash::Hasher") . [Read more](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html#method.hash_slice) 1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1191) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Mul%3CDuration%3E-for-u32) ### impl [Mul](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html "trait std::ops::Mul") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1192) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-4) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html#associatedtype.Output) = [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") The resulting type after applying the `*` operator. [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1195) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.mul-1) #### fn [mul](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html#tymethod.mul) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Performs the `*` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html#tymethod.mul) 1.3.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1180) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Mul%3Cu32%3E-for-Duration) ### impl [Mul](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html "trait std::ops::Mul") <[u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) \> for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1181) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-3) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html#associatedtype.Output) = [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") The resulting type after applying the `*` operator. [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1184) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.mul) #### fn [mul](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html#tymethod.mul) (self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Performs the `*` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html#tymethod.mul) 1.9.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1202) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-MulAssign%3Cu32%3E-for-Duration) ### impl [MulAssign](https://doc.rust-lang.org/stable/std/ops/trait.MulAssign.html "trait std::ops::MulAssign") <[u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) \> for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1204) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.mul_assign) #### fn [mul\_assign](https://doc.rust-lang.org/stable/std/ops/trait.MulAssign.html#tymethod.mul_assign) (&mut self, rhs: [u32](https://doc.rust-lang.org/stable/std/primitive.u32.html) ) Performs the `*=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.MulAssign.html#tymethod.mul_assign) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Ord-for-Duration) ### impl [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.cmp) #### fn [cmp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) (&self, other: &[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") This method returns an [`Ordering`](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") between `self` and `other`. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#tymethod.cmp) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1021-1023) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.max) #### fn [max](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the maximum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.max) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1060-1062) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.min) #### fn [min](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) (self, other: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Compares and returns the minimum of two values. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.min) 1.50.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1086-1088) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.clamp) #### fn [clamp](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) (self, min: Self, max: Self) -> Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Restrict a value to a certain interval. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#method.clamp) 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-PartialEq-for-Duration) ### impl [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#tymethod.eq) (&self, other: &[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#264) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html#method.ne) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-PartialOrd-for-Duration) ### impl [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.partial_cmp) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) (&self, other: &[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> This method returns an ordering between `self` and `other` values if one exists. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1398) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.lt) #### fn [lt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.lt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1416) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.le) #### fn [le](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.le) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1434) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.gt) #### fn [gt](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.gt) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/cmp.rs.html#1452) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.ge) #### fn [ge](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) (&self, other: [&Rhs](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html#method.ge) 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#442-448) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Sub%3CDuration%3E-for-Instant) ### impl [Sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html "trait std::ops::Sub") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#443) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-6) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#associatedtype.Output) = [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") The resulting type after applying the `-` operator. [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#445-447) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sub-1) #### fn [sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#tymethod.sub) (self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") Performs the `-` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#tymethod.sub) 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#626-632) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Sub%3CDuration%3E-for-SystemTime) ### impl [Sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html "trait std::ops::Sub") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#627) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-8) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#associatedtype.Output) = [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") The resulting type after applying the `-` operator. [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#629-631) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sub-2) #### fn [sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#tymethod.sub) (self, dur: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") Performs the `-` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#tymethod.sub) 1.3.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1160) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Sub-for-Duration) ### impl [Sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html "trait std::ops::Sub") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1161) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Output-2) #### type [Output](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#associatedtype.Output) = [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") The resulting type after applying the `-` operator. [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1164) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sub) #### fn [sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#tymethod.sub) (self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Performs the `-` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html#tymethod.sub) 1.9.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#451-455) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-SubAssign%3CDuration%3E-for-Instant) ### impl [SubAssign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html "trait std::ops::SubAssign") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#452-454) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sub_assign-1) #### fn [sub\_assign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html#tymethod.sub_assign) (&mut self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) Performs the `-=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html#tymethod.sub_assign) 1.9.0 · [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#635-639) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-SubAssign%3CDuration%3E-for-SystemTime) ### impl [SubAssign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html "trait std::ops::SubAssign") <[Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [SystemTime](https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html "struct std::time::SystemTime") [Source](https://doc.rust-lang.org/stable/src/std/time.rs.html#636-638) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sub_assign-2) #### fn [sub\_assign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html#tymethod.sub_assign) (&mut self, other: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) Performs the `-=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html#tymethod.sub_assign) 1.9.0 (const: [unstable](https://github.com/rust-lang/rust/issues/143802 "Tracking issue for const_ops") ) · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1171) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-SubAssign-for-Duration) ### impl [SubAssign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html "trait std::ops::SubAssign") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1173) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sub_assign) #### fn [sub\_assign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html#tymethod.sub_assign) (&mut self, rhs: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) Performs the `-=` operation. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html#tymethod.sub_assign) 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1265) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Sum%3C%26Duration%3E-for-Duration) ### impl<'a> [Sum](https://doc.rust-lang.org/stable/std/iter/trait.Sum.html "trait std::iter::Sum") <&'a [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") \> for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1266) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sum-1) #### fn [sum](https://doc.rust-lang.org/stable/std/iter/trait.Sum.html#tymethod.sum) (iter: I) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") where I: [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , Takes an iterator and generates `Self` from the elements by “summing up” the items. 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1258) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Sum-for-Duration) ### impl [Sum](https://doc.rust-lang.org/stable/std/iter/trait.Sum.html "trait std::iter::Sum") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#1259) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.sum) #### fn [sum](https://doc.rust-lang.org/stable/std/iter/trait.Sum.html#tymethod.sum) (iter: I) -> [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") where I: [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , Takes an iterator and generates `Self` from the elements by “summing up” the items. 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Copy-for-Duration) ### impl [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Eq-for-Duration) ### impl [Eq](https://doc.rust-lang.org/stable/std/cmp/trait.Eq.html "trait std::cmp::Eq") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") 1.3.0 · [Source](https://doc.rust-lang.org/stable/src/core/time.rs.html#79) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-StructuralPartialEq-for-Duration) ### impl [StructuralPartialEq](https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html "trait std::marker::StructuralPartialEq") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Freeze-for-Duration) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-RefUnwindSafe-for-Duration) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Send-for-Duration) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Sync-for-Duration) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Unpin-for-Duration) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-UnwindSafe-for-Duration) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # LazyLock in std::sync - Rust [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#) ---------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) Struct LazyLock Copy item path ============================== 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#81-85) pub struct LazyLock T> { /* private fields */ } Expand description A value which is initialized on the first access. This type is a thread-safe [`LazyCell`](https://doc.rust-lang.org/stable/std/cell/struct.LazyCell.html "struct std::cell::LazyCell") , and can be used in statics. Since initialization may be called from multiple threads, any dereferencing call will block the calling thread if another initialization routine is currently running. [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#poisoning) Poisoning --------------------------------------------------------------------------------------- If the initialization closure passed to [`LazyLock::new`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.new "associated function std::sync::LazyLock::new") panics, the lock will be poisoned. Once the lock is poisoned, any threads that attempt to access this lock (via a dereference or via an explicit call to [`force()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force "associated function std::sync::LazyLock::force") ) will panic. This concept is similar to that of poisoning in the [`std::sync::poison`](https://doc.rust-lang.org/stable/std/sync/poison/index.html "mod std::sync::poison") module. A key difference, however, is that poisoning in `LazyLock` is _unrecoverable_. All future accesses of the lock from other threads will panic, whereas a type in [`std::sync::poison`](https://doc.rust-lang.org/stable/std/sync/poison/index.html "mod std::sync::poison") like [`std::sync::poison::Mutex`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html "struct std::sync::Mutex") allows recovery via [`PoisonError::into_inner()`](https://doc.rust-lang.org/stable/std/sync/struct.PoisonError.html#method.into_inner "method std::sync::PoisonError::into_inner") . [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples) Examples ------------------------------------------------------------------------------------- Initialize static variables with `LazyLock`. use std::sync::LazyLock; // Note: static items do not call [`Drop`] on program termination, so this won't be deallocated. // this is fine, as the OS can deallocate the terminated program faster than we can free memory // but tools like valgrind might report "memory leaks" as it isn't obvious this is intentional. static DEEP_THOUGHT: LazyLock = LazyLock::new(|| { // M3 Ultra takes about 16 million years in --release config another_crate::great_question() }); // The `String` is built, stored in the `LazyLock`, and returned as `&String`. let _ = &*DEEP_THOUGHT; [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++//+Note:+static+items+do+not+call+%5B%60Drop%60%5D+on+program+termination,+so+this+won%27t+be+deallocated.%0A++++//+this+is+fine,+as+the+OS+can+deallocate+the+terminated+program+faster+than+we+can+free+memory%0A++++//+but+tools+like+valgrind+might+report+%22memory+leaks%22+as+it+isn%27t+obvious+this+is+intentional.%0A++++static+DEEP_THOUGHT:+LazyLock%3CString%3E+=+LazyLock::new(%7C%7C+%7B%0A++++mod+another_crate+%7B%0A++++++++pub+fn+great_question()+-%3E+String+%7B+%2242%22.to_string()+%7D%0A++++%7D%0A++++++++//+M3+Ultra+takes+about+16+million+years+in+--release+config%0A++++++++another_crate::great_question()%0A++++%7D);%0A++++%0A++++//+The+%60String%60+is+built,+stored+in+the+%60LazyLock%60,+and+returned+as+%60%26String%60.%0A++++let+_+=+%26*DEEP_THOUGHT;%0A%7D&edition=2024 "Run code") Initialize fields with `LazyLock`. use std::sync::LazyLock; #[derive(Debug)] struct UseCellLock { number: LazyLock, } fn main() { let lock: LazyLock = LazyLock::new(|| 0u32); let data = UseCellLock { number: lock }; println!("{}", *data.number); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Ause+std::sync::LazyLock;%0A%0A%23%5Bderive(Debug)%5D%0Astruct+UseCellLock+%7B%0A++++number:+LazyLock%3Cu32%3E,%0A%7D%0Afn+main()+%7B%0A++++let+lock:+LazyLock%3Cu32%3E+=+LazyLock::new(%7C%7C+0u32);%0A%0A++++let+data+=+UseCellLock+%7B+number:+lock+%7D;%0A++++println!(%22%7B%7D%22,+*data.number);%0A%7D&edition=2024 "Run code") Implementations[§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#implementations) --------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#87-272) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-LazyLock%3CT,+F%3E) ### impl T> [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") 1.80.0 (const: 1.80.0) · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#104-106) #### pub const fn [new](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.new) (f: F) -> [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") Creates a new lazy value with the given initializing function. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples-1) Examples use std::sync::LazyLock; let hello = "Hello, World!".to_string(); let lazy = LazyLock::new(|| hello.to_uppercase()); assert_eq!(&*lazy, "HELLO, WORLD!"); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++let+hello+=+%22Hello,+World!%22.to_string();%0A++++%0A++++let+lazy+=+LazyLock::new(%7C%7C+hello.to_uppercase());%0A++++%0A++++assert_eq!(%26*lazy,+%22HELLO,+WORLD!%22);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#140-158) #### pub fn [into\_inner](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.into_inner) (this: Self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") 🔬This is a nightly-only experimental API. (`lazy_cell_into_inner` [#125623](https://github.com/rust-lang/rust/issues/125623) ) Consumes this `LazyLock` returning the stored value. Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#panics) Panics Panics if the lock is poisoned. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples-2) Examples #![feature(lazy_cell_into_inner)] use std::sync::LazyLock; let hello = "Hello, World!".to_string(); let lazy = LazyLock::new(|| hello.to_uppercase()); assert_eq!(&*lazy, "HELLO, WORLD!"); assert_eq!(LazyLock::into_inner(lazy).ok(), Some("HELLO, WORLD!".to_string())); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(lazy_cell_into_inner)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++let+hello+=+%22Hello,+World!%22.to_string();%0A++++%0A++++let+lazy+=+LazyLock::new(%7C%7C+hello.to_uppercase());%0A++++%0A++++assert_eq!(%26*lazy,+%22HELLO,+WORLD!%22);%0A++++assert_eq!(LazyLock::into_inner(lazy).ok(),+Some(%22HELLO,+WORLD!%22.to_string()));%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#187-221) #### pub fn [force\_mut](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force_mut) (this: &mut [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") ) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) 🔬This is a nightly-only experimental API. (`lazy_get` [#129333](https://github.com/rust-lang/rust/issues/129333) ) Forces the evaluation of this lazy value and returns a mutable reference to the result. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#panics-1) Panics If the initialization closure panics (the one that is passed to the [`new()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.new "associated function std::sync::LazyLock::new") method), the panic is propagated to the caller, and the lock becomes poisoned. This will cause all future accesses of the lock (via [`force()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force "associated function std::sync::LazyLock::force") or a dereference) to panic. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples-3) Examples #![feature(lazy_get)] use std::sync::LazyLock; let mut lazy = LazyLock::new(|| 92); let p = LazyLock::force_mut(&mut lazy); assert_eq!(*p, 92); *p = 44; assert_eq!(*lazy, 44); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(lazy_get)%5D%0A%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++let+mut+lazy+=+LazyLock::new(%7C%7C+92);%0A++++%0A++++let+p+=+LazyLock::force_mut(%26mut+lazy);%0A++++assert_eq!(*p,+92);%0A++++*p+=+44;%0A++++assert_eq!(*lazy,+44);%0A%7D&version=nightly&edition=2024 "Run code") 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#250-271) #### pub fn [force](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force) (this: &[LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") ) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Forces the evaluation of this lazy value and returns a reference to result. This is equivalent to the `Deref` impl, but is explicit. This method will block the calling thread if another initialization routine is currently running. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#panics-2) Panics If the initialization closure panics (the one that is passed to the [`new()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.new "associated function std::sync::LazyLock::new") method), the panic is propagated to the caller, and the lock becomes poisoned. This will cause all future accesses of the lock (via [`force()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force "associated function std::sync::LazyLock::force") or a dereference) to panic. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples-4) Examples use std::sync::LazyLock; let lazy = LazyLock::new(|| 92); assert_eq!(LazyLock::force(&lazy), &92); assert_eq!(&*lazy, &92); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++let+lazy+=+LazyLock::new(%7C%7C+92);%0A++++%0A++++assert_eq!(LazyLock::force(%26lazy),+%2692);%0A++++assert_eq!(%26*lazy,+%2692);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#274-333) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-LazyLock%3CT,+F%3E-1) ### impl [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#294-303) #### pub fn [get\_mut](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.get_mut) (this: &mut [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> 🔬This is a nightly-only experimental API. (`lazy_get` [#129333](https://github.com/rust-lang/rust/issues/129333) ) Returns a mutable reference to the value if initialized. Otherwise (if uninitialized or poisoned), returns `None`. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples-5) Examples #![feature(lazy_get)] use std::sync::LazyLock; let mut lazy = LazyLock::new(|| 92); assert_eq!(LazyLock::get_mut(&mut lazy), None); let _ = LazyLock::force(&lazy); *LazyLock::get_mut(&mut lazy).unwrap() = 44; assert_eq!(*lazy, 44); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(lazy_get)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++let+mut+lazy+=+LazyLock::new(%7C%7C+92);%0A++++%0A++++assert_eq!(LazyLock::get_mut(%26mut+lazy),+None);%0A++++let+_+=+LazyLock::force(%26lazy);%0A++++*LazyLock::get_mut(%26mut+lazy).unwrap()+=+44;%0A++++assert_eq!(*lazy,+44);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#323-332) #### pub fn [get](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.get) (this: &[LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) \> 🔬This is a nightly-only experimental API. (`lazy_get` [#129333](https://github.com/rust-lang/rust/issues/129333) ) Returns a reference to the value if initialized. Otherwise (if uninitialized or poisoned), returns `None`. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#examples-6) Examples #![feature(lazy_get)] use std::sync::LazyLock; let lazy = LazyLock::new(|| 92); assert_eq!(LazyLock::get(&lazy), None); let _ = LazyLock::force(&lazy); assert_eq!(LazyLock::get(&lazy), Some(&92)); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(lazy_get)%5D%0A%0A%0Afn+main()+%7B%0A++++use+std::sync::LazyLock;%0A++++%0A++++let+lazy+=+LazyLock::new(%7C%7C+92);%0A++++%0A++++assert_eq!(LazyLock::get(%26lazy),+None);%0A++++let+_+=+LazyLock::force(%26lazy);%0A++++assert_eq!(LazyLock::get(%26lazy),+Some(%2692));%0A%7D&version=nightly&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#trait-implementations) --------------------------------------------------------------------------------------------------------------- 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#399-408) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Debug-for-LazyLock%3CT,+F%3E) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#400-407) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#390-396) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Default-for-LazyLock%3CT%3E) ### impl [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#393-395) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.default) #### fn [default](https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default) () -> [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") Creates a new lazy value using `Default` as the initializing function. 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#351-371) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Deref-for-LazyLock%3CT,+F%3E) ### impl T> [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#368-370) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.deref) #### fn [deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#tymethod.deref) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Dereferences the value. This method will block the calling thread if another initialization routine is currently running. ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#panics-3) Panics If the initialization closure panics (the one that is passed to the [`new()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.new "associated function std::sync::LazyLock::new") method), the panic is propagated to the caller, and the lock becomes poisoned. This will cause all future accesses of the lock (via [`force()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force "associated function std::sync::LazyLock::force") or a dereference) to panic. [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#352) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#associatedtype.Target) #### type [Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target) = T The resulting type after dereferencing. 1.89.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#374-387) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-DerefMut-for-LazyLock%3CT,+F%3E) ### impl T> [DerefMut](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "trait std::ops::DerefMut") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#384-386) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.deref_mut) #### fn [deref\_mut](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html#tymethod.deref_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ##### [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#panics-4) Panics If the initialization closure panics (the one that is passed to the [`new()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.new "associated function std::sync::LazyLock::new") method), the panic is propagated to the caller, and the lock becomes poisoned. This will cause all future accesses of the lock (via [`force()`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.force "associated function std::sync::LazyLock::force") or a dereference) to panic. 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#336-348) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Drop-for-LazyLock%3CT,+F%3E) ### impl [Drop](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#337-347) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.drop) #### fn [drop](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop) (&mut self) Executes the destructor for this type. [Read more](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html#tymethod.drop) 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#423) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-RefUnwindSafe-for-LazyLock%3CT,+F%3E) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#419) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Sync-for-LazyLock%3CT,+F%3E) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") 1.80.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/lazy_lock.rs.html#425) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-UnwindSafe-for-LazyLock%3CT,+F%3E) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#synthetic-implementations) ------------------------------------------------------------------------------------------------------------------------ [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Freeze-for-LazyLock%3CT,+F%3E) ### impl T> ![Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Send-for-LazyLock%3CT,+F%3E) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") where T: [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") , F: [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") , [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Unpin-for-LazyLock%3CT,+F%3E) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [LazyLock](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html "struct std::sync::LazyLock") where T: [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , F: [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") , Blanket Implementations[§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#378-380) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-Receiver-for-P) ### impl [Receiver](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html "trait std::ops::Receiver") for P where P: [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#382) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#associatedtype.Target-1) #### type [Target](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#associatedtype.Target) = T 🔬This is a nightly-only experimental API. (`arbitrary_self_types` [#44874](https://github.com/rust-lang/rust/issues/44874) ) The target type on which the method may be called. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # EncodeUtf16 in std::str - Rust [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) --------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[str](https://doc.rust-lang.org/stable/std/str/index.html) Struct EncodeUtf16 Copy item path ================================= 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1489) pub struct EncodeUtf16<'a> { /* private fields */ } Expand description An iterator of [`u16`](https://doc.rust-lang.org/stable/std/primitive.u16.html "primitive u16") over the string encoded as UTF-16. This struct is created by the [`encode_utf16`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.encode_utf16 "method str::encode_utf16") method on [`str`](https://doc.rust-lang.org/stable/std/primitive.str.html "primitive str") . See its documentation for more. Trait Implementations[§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#trait-implementations) ----------------------------------------------------------------------------------------------------------------- 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1487) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Clone-for-EncodeUtf16%3C'a%3E) ### impl<'a> [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1487) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.clone) #### fn [clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) (&self) -> [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) Returns a duplicate of the value. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#245-247) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.clone_from) #### fn [clone\_from](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) (&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#method.clone_from) 1.17.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1495) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Debug-for-EncodeUtf16%3C'_%3E) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'\_> [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1496) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [Error](https://doc.rust-lang.org/stable/std/fmt/struct.Error.html "struct std::fmt::Error") \> Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1502) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Iterator-for-EncodeUtf16%3C'a%3E) ### impl<'a> [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1503) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#associatedtype.Item) #### type [Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item) = [u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) The type of the elements being iterated over. [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1506) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.next) #### fn [next](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#tymethod.next) (&mut self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[u16](https://doc.rust-lang.org/stable/std/primitive.u16.html) \> Advances the iterator and returns the next value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#tymethod.next) [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1524) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.size_hint) #### fn [size\_hint](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint) (&self) -> ([usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) , [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) \>) Returns the bounds on the remaining length of the iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#110-114) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.next_chunk) #### fn [next\_chunk](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.next_chunk) ( &mut self, ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <\[Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item")\ ; [N](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \], [IntoIter](https://doc.rust-lang.org/stable/std/array/struct.IntoIter.html "struct std::array::IntoIter") > where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326) ) Advances the iterator and returns an array containing the next `N` values. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.next_chunk) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#222-224) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.count) #### fn [count](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.count) (self) -> [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Consumes the iterator, counting the number of iterations and returning it. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.count) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#250-252) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.last) #### fn [last](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.last) (self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Consumes the iterator, returning the last element. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.last) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#297) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.advance_by) #### fn [advance\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.advance_by) (&mut self, n: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[()](https://doc.rust-lang.org/stable/std/primitive.unit.html) , [NonZero](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html "struct std::num::NonZero") <[usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) \>> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404) ) Advances the iterator by `n` elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.advance_by) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#374) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.nth) #### fn [nth](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.nth) (&mut self, n: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") Returns the `n`th element of the iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.nth) 1.28.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#424-426) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.step_by) #### fn [step\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.step_by) (self, step: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [StepBy](https://doc.rust-lang.org/stable/std/iter/struct.StepBy.html "struct std::iter::StepBy") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.step_by) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#495-498) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.chain) #### fn [chain](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.chain) (self, other: U) -> [Chain](https://doc.rust-lang.org/stable/std/iter/struct.Chain.html "struct std::iter::Chain") ::[IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter "type std::iter::IntoIterator::IntoIter") \> [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , U: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Takes two iterators and creates a new iterator over both in sequence. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.chain) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#613-616) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.zip) #### fn [zip](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.zip) (self, other: U) -> [Zip](https://doc.rust-lang.org/stable/std/iter/struct.Zip.html "struct std::iter::Zip") ::[IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter "type std::iter::IntoIterator::IntoIter") \> [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , U: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , ‘Zips up’ two iterators into a single iterator of pairs. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.zip) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#656-659) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.intersperse) #### fn [intersperse](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.intersperse) (self, separator: Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Intersperse](https://doc.rust-lang.org/stable/std/iter/struct.Intersperse.html "struct std::iter::Intersperse") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524) ) Creates a new iterator which places a copy of `separator` between adjacent items of the original iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.intersperse) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#714-717) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.intersperse_with) #### fn [intersperse\_with](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.intersperse_with) (self, separator: G) -> [IntersperseWith](https://doc.rust-lang.org/stable/std/iter/struct.IntersperseWith.html "struct std::iter::IntersperseWith") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , G: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") () -> Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524) ) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.intersperse_with) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#773-776) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.map) #### fn [map](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map) (self, f: F) -> [Map](https://doc.rust-lang.org/stable/std/iter/struct.Map.html "struct std::iter::Map") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> B, Takes a closure and creates an iterator which calls that closure on each element. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map) 1.21.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#818-821) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.for_each) #### fn [for\_each](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.for_each) (self, f: F) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ), Calls a closure on each element of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.for_each) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#893-896) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.filter) #### fn [filter](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter)

(self, predicate: P) -> [Filter](https://doc.rust-lang.org/stable/std/iter/struct.Filter.html "struct std::iter::Filter") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#938-941) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.filter_map) #### fn [filter\_map](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter_map) (self, f: F) -> [FilterMap](https://doc.rust-lang.org/stable/std/iter/struct.FilterMap.html "struct std::iter::FilterMap") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , Creates an iterator that both filters and maps. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter_map) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#985-987) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.enumerate) #### fn [enumerate](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.enumerate) (self) -> [Enumerate](https://doc.rust-lang.org/stable/std/iter/struct.Enumerate.html "struct std::iter::Enumerate") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates an iterator which gives the current iteration count as well as the next value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.enumerate) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1056-1058) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.peekable) #### fn [peekable](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.peekable) (self) -> [Peekable](https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html "struct std::iter::Peekable") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates an iterator which can use the [`peek`](https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html#method.peek "method std::iter::Peekable::peek") and [`peek_mut`](https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html#method.peek_mut "method std::iter::Peekable::peek_mut") methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.peekable) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1121-1124) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.skip_while) #### fn [skip\_while](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip_while)

(self, predicate: P) -> [SkipWhile](https://doc.rust-lang.org/stable/std/iter/struct.SkipWhile.html "struct std::iter::SkipWhile") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Creates an iterator that [`skip`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip "method std::iter::Iterator::skip") s elements based on a predicate. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip_while) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1199-1202) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.take_while) #### fn [take\_while](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take_while)

(self, predicate: P) -> [TakeWhile](https://doc.rust-lang.org/stable/std/iter/struct.TakeWhile.html "struct std::iter::TakeWhile") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Creates an iterator that yields elements based on a predicate. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take_while) 1.57.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1287-1290) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.map_while) #### fn [map\_while](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map_while) (self, predicate: P) -> [MapWhile](https://doc.rust-lang.org/stable/std/iter/struct.MapWhile.html "struct std::iter::MapWhile") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , Creates an iterator that both yields elements based on a predicate and maps. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map_while) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1316-1318) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.skip) #### fn [skip](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip) (self, n: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Skip](https://doc.rust-lang.org/stable/std/iter/struct.Skip.html "struct std::iter::Skip") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates an iterator that skips the first `n` elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1388-1390) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.take) #### fn [take](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take) (self, n: [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) ) -> [Take](https://doc.rust-lang.org/stable/std/iter/struct.Take.html "struct std::iter::Take") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1435-1438) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.scan) #### fn [scan](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.scan) (self, initial\_state: St, f: F) -> [Scan](https://doc.rust-lang.org/stable/std/iter/struct.Scan.html "struct std::iter::Scan") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") ([&mut St](https://doc.rust-lang.org/stable/std/primitive.reference.html) , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , An iterator adapter which, like [`fold`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fold "method std::iter::Iterator::fold") , holds internal state, but unlike [`fold`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fold "method std::iter::Iterator::fold") , produces a new iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.scan) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1473-1477) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.flat_map) #### fn [flat\_map](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flat_map) (self, f: F) -> [FlatMap](https://doc.rust-lang.org/stable/std/iter/struct.FlatMap.html "struct std::iter::FlatMap") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , U: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> U, Creates an iterator that works like map, but flattens nested structure. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flat_map) 1.29.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1557-1560) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.flatten) #### fn [flatten](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flatten) (self) -> [Flatten](https://doc.rust-lang.org/stable/std/iter/struct.Flatten.html "struct std::iter::Flatten") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Creates an iterator that flattens nested structure. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flatten) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1713-1716) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.map_windows) #### fn [map\_windows](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map_windows) (self, f: F) -> [MapWindows](https://doc.rust-lang.org/stable/std/iter/struct.MapWindows.html "struct std::iter::MapWindows") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&\[Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item")\ ; [N](https://doc.rust-lang.org/stable/std/primitive.array.html)\ \]) -> R, 🔬This is a nightly-only experimental API. (`iter_map_windows` [#87155](https://github.com/rust-lang/rust/issues/87155) ) Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.windows "method slice::windows") , the windows during mapping overlap as well. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map_windows) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1775-1777) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.fuse) #### fn [fuse](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fuse) (self) -> [Fuse](https://doc.rust-lang.org/stable/std/iter/struct.Fuse.html "struct std::iter::Fuse") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates an iterator which ends after the first [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") . [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fuse) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1859-1862) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.inspect) #### fn [inspect](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.inspect) (self, f: F) -> [Inspect](https://doc.rust-lang.org/stable/std/iter/struct.Inspect.html "struct std::iter::Inspect") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ), Does something with each element of an iterator, passing the value on. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.inspect) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#1896-1898) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.by_ref) #### fn [by\_ref](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.by_ref) (&mut self) -> &mut Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Creates a “by reference” adapter for this instance of `Iterator`. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.by_ref) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2015-2017) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.collect) #### fn [collect](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect) (self) -> B where B: [FromIterator](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html "trait std::iter::FromIterator") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Transforms an iterator into a collection. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2102-2106) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_collect) #### fn [try\_collect](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_collect) ( &mut self, ) -> <::[Residual](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Residual "type std::ops::Try::Residual") as [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") >::[TryType](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html#associatedtype.TryType "type std::ops::Residual::TryType") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [Try](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , ::[Residual](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Residual "type std::ops::Try::Residual") : [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") , B: [FromIterator](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html "trait std::iter::FromIterator") <::[Output](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Output "type std::ops::Try::Output") \>, 🔬This is a nightly-only experimental API. (`iterator_try_collect` [#94047](https://github.com/rust-lang/rust/issues/94047) ) Fallibly transforms an iterator into a collection, short circuiting if a failure is encountered. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_collect) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2174-2176) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.collect_into) #### fn [collect\_into](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect_into) (self, collection: [&mut E](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [&mut E](https://doc.rust-lang.org/stable/std/primitive.reference.html) where E: [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780) ) Collects all the items from an iterator into a collection. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect_into) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2206-2210) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.partition) #### fn [partition](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partition) (self, f: F) -> [(B, B)](https://doc.rust-lang.org/stable/std/primitive.tuple.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , B: [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") + [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Consumes an iterator, creating two collections from it. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partition) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2268-2271) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.partition_in_place) #### fn [partition\_in\_place](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partition_in_place) <'a, T, P>(self, predicate: P) -> [usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) where T: 'a, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [DoubleEndedIterator](https://doc.rust-lang.org/stable/std/iter/trait.DoubleEndedIterator.html "trait std::iter::DoubleEndedIterator") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") ([&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543) ) Reorders the elements of this iterator _in-place_ according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partition_in_place) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2325-2328) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.is_partitioned) #### fn [is\_partitioned](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_partitioned)

(self, predicate: P) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544) ) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_partitioned) 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2419-2423) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_fold) #### fn [try\_fold](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_fold) (&mut self, init: B, f: F) -> R where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (B, Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> R, R: [Try](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_fold) 1.27.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2477-2481) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_for_each) #### fn [try\_for\_each](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_for_each) (&mut self, f: F) -> R where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> R, R: [Try](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_for_each) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2596-2599) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.fold) #### fn [fold](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fold) (self, init: B, f: F) -> B where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (B, Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fold) 1.51.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2633-2636) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.reduce) #### fn [reduce](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.reduce) (self, f: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.reduce) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2704-2710) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_reduce) #### fn [try\_reduce](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_reduce) ( &mut self, f: impl [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> R, ) -> <::[Residual](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Residual "type std::ops::Try::Residual") as [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") <[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <::[Output](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Output "type std::ops::Try::Output") \>>>::[TryType](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html#associatedtype.TryType "type std::ops::Residual::TryType") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , R: [Try](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , ::[Residual](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Residual "type std::ops::Try::Residual") : [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") <[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") >, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053) ) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_reduce) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2762-2765) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.all) #### fn [all](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.all) (&mut self, f: F) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Tests if every element of the iterator matches a predicate. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.all) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2815-2818) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.any) #### fn [any](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.any) (&mut self, f: F) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Tests if any element of the iterator matches a predicate. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.any) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2877-2880) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.find) #### fn [find](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find)

(&mut self, predicate: P) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Searches for an element of an iterator that satisfies a predicate. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find) 1.30.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2908-2911) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.find_map) #### fn [find\_map](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find_map) (&mut self, f: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") , Applies function to the elements of iterator and returns the first non-none result. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find_map) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#2966-2972) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_find) #### fn [try\_find](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_find) ( &mut self, f: impl [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> R, ) -> <::[Residual](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Residual "type std::ops::Try::Residual") as [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") <[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") >>::[TryType](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html#associatedtype.TryType "type std::ops::Residual::TryType") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , R: [Try](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") , ::[Residual](https://doc.rust-lang.org/stable/std/ops/trait.Try.html#associatedtype.Residual "type std::ops::Try::Residual") : [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") <[Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") >, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178) ) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_find) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3049-3052) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.position) #### fn [position](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.position)

(&mut self, predicate: P) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) \> where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Searches for an element in an iterator, returning its index. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.position) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3114-3117) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.rposition) #### fn [rposition](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.rposition)

(&mut self, predicate: P) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[usize](https://doc.rust-lang.org/stable/std/primitive.usize.html) \> where P: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [ExactSizeIterator](https://doc.rust-lang.org/stable/std/iter/trait.ExactSizeIterator.html "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](https://doc.rust-lang.org/stable/std/iter/trait.DoubleEndedIterator.html "trait std::iter::DoubleEndedIterator") , Searches for an element in an iterator from the right, returning its index. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.rposition) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3163-3166) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.max) #### fn [max](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max) (self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Returns the maximum element of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3199-3202) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.min) #### fn [min](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min) (self) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Returns the minimum element of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min) 1.6.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3221-3224) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.max_by_key) #### fn [max\_by\_key](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max_by_key) (self, f: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where B: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> B, Returns the element that gives the maximum value from the specified function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max_by_key) 1.15.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3254-3257) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.max_by) #### fn [max\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max_by) (self, compare: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , &Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") , Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max_by) 1.6.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3281-3284) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.min_by_key) #### fn [min\_by\_key](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min_by_key) (self, f: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where B: [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> B, Returns the element that gives the minimum value from the specified function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min_by_key) 1.15.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3314-3317) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.min_by) #### fn [min\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min_by) (self, compare: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , &Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") , Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min_by) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3351-3353) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.rev) #### fn [rev](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.rev) (self) -> [Rev](https://doc.rust-lang.org/stable/std/iter/struct.Rev.html "struct std::iter::Rev") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [DoubleEndedIterator](https://doc.rust-lang.org/stable/std/iter/trait.DoubleEndedIterator.html "trait std::iter::DoubleEndedIterator") , Reverses an iterator’s direction. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.rev) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3387-3391) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.unzip) #### fn [unzip](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.unzip) (self) -> [(FromA, FromB)](https://doc.rust-lang.org/stable/std/primitive.tuple.html) where FromA: [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") + [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") , FromB: [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") + [Extend](https://doc.rust-lang.org/stable/std/iter/trait.Extend.html "trait std::iter::Extend") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , Converts an iterator of pairs into a pair of containers. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.unzip) 1.36.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3418-3421) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.copied) #### fn [copied](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.copied) <'a, T>(self) -> [Copied](https://doc.rust-lang.org/stable/std/iter/struct.Copied.html "struct std::iter::Copied") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where T: [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") + 'a, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , Creates an iterator which copies all of its elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.copied) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3466-3469) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.cloned) #### fn [cloned](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cloned) <'a, T>(self) -> [Cloned](https://doc.rust-lang.org/stable/std/iter/struct.Cloned.html "struct std::iter::Cloned") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") + 'a, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , Creates an iterator which [`clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone "method std::clone::Clone::clone") s all of its elements. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cloned) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3497-3499) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.cycle) #### fn [cycle](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cycle) (self) -> [Cycle](https://doc.rust-lang.org/stable/std/iter/struct.Cycle.html "struct std::iter::Cycle") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") + [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , Repeats an iterator endlessly. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cycle) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3540-3542) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.array_chunks) #### fn [array\_chunks](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.array_chunks) (self) -> [ArrayChunks](https://doc.rust-lang.org/stable/std/iter/struct.ArrayChunks.html "struct std::iter::ArrayChunks") [ⓘ](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450) ) Returns an iterator over `N` elements of the iterator at a time. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.array_chunks) 1.11.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3576-3579) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.sum) #### fn [sum](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.sum) (self) -> S where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , S: [Sum](https://doc.rust-lang.org/stable/std/iter/trait.Sum.html "trait std::iter::Sum") , Sums the elements of an iterator. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.sum) 1.11.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3608-3611) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.product) #### fn [product](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.product)

(self) -> P where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , P: [Product](https://doc.rust-lang.org/stable/std/iter/trait.Product.html "trait std::iter::Product") , Iterates over the entire iterator, multiplying all the elements [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.product) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3629-3633) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.cmp) #### fn [cmp](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cmp) (self, other: I) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [Ord](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html "trait std::cmp::Ord") , Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") compares the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") with those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cmp) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3656-3660) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.cmp_by) #### fn [cmp\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cmp_by) (self, other: I, cmp: F) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , ::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") ) -> [Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") , 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295) ) [Lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") compares the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") with those of another with respect to the specified comparison function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cmp_by) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3712-3716) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.partial_cmp) #### fn [partial\_cmp](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partial_cmp) (self, other: I) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") compares the [`PartialOrd`](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") with those of another. The comparison works like short-circuit evaluation, returning a result without comparing the remaining elements. As soon as an order can be determined, the evaluation stops and a result is returned. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partial_cmp) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3748-3752) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.partial_cmp_by) #### fn [partial\_cmp\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partial_cmp_by) (self, other: I, partial\_cmp: F) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \> where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , ::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") ) -> [Option](https://doc.rust-lang.org/stable/std/option/enum.Option.html "enum std::option::Option") <[Ordering](https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html "enum std::cmp::Ordering") \>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295) ) [Lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") compares the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") with those of another with respect to the specified comparison function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partial_cmp_by) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3781-3785) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.eq) #### fn [eq](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.eq) (self, other: I) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are equal to those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.eq) [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3804-3808) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.eq_by) #### fn [eq\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.eq_by) (self, other: I, eq: F) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , ::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295) ) Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are equal to those of another with respect to the specified equality function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.eq_by) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3833-3837) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.ne) #### fn [ne](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.ne) (self, other: I) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialEq](https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html "trait std::cmp::PartialEq") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are not equal to those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.ne) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3854-3858) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.lt) #### fn [lt](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.lt) (self, other: I) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") less than those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.lt) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3875-3879) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.le) #### fn [le](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.le) (self, other: I) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") less or equal to those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.le) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3896-3900) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.gt) #### fn [gt](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.gt) (self, other: I) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") greater than those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.gt) 1.5.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3917-3921) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.ge) #### fn [ge](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.ge) (self, other: I) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where I: [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") <::[Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item "type std::iter::IntoIterator::Item") \>, Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Determines if the elements of this [`Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") are [lexicographically](https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html#lexicographical-comparison "trait std::cmp::Ord") greater than or equal to those of another. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.ge) 1.82.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3946-3949) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.is_sorted) #### fn [is\_sorted](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_sorted) (self) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") : [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , Checks if the elements of this iterator are sorted. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_sorted) 1.82.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#3972-3975) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.is_sorted_by) #### fn [is\_sorted\_by](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_sorted_by) (self, compare: F) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") , &Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) , Checks if the elements of this iterator are sorted using the given comparator function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_sorted_by) 1.82.0 · [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/iterator.rs.html#4016-4020) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.is_sorted_by_key) #### fn [is\_sorted\_by\_key](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_sorted_by_key) (self, f: F) -> [bool](https://doc.rust-lang.org/stable/std/primitive.bool.html) where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (Self::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") ) -> K, K: [PartialOrd](https://doc.rust-lang.org/stable/std/cmp/trait.PartialOrd.html "trait std::cmp::PartialOrd") , Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.is_sorted_by_key) 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/core/str/iter.rs.html#1545) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-FusedIterator-for-EncodeUtf16%3C'_%3E) ### impl [FusedIterator](https://doc.rust-lang.org/stable/std/iter/trait.FusedIterator.html "trait std::iter::FusedIterator") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'\_> Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#synthetic-implementations) -------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Freeze-for-EncodeUtf16%3C'a%3E) ### impl<'a> [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-RefUnwindSafe-for-EncodeUtf16%3C'a%3E) ### impl<'a> [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Send-for-EncodeUtf16%3C'a%3E) ### impl<'a> [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Sync-for-EncodeUtf16%3C'a%3E) ### impl<'a> [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Unpin-for-EncodeUtf16%3C'a%3E) ### impl<'a> [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-UnwindSafe-for-EncodeUtf16%3C'a%3E) ### impl<'a> [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [EncodeUtf16](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html "struct std::str::EncodeUtf16") <'a> Blanket Implementations[§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#blanket-implementations) --------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#515) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-CloneToUninit-for-T) ### impl [CloneToUninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html "trait std::clone::CloneToUninit") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/core/clone.rs.html#517) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.clone_to_uninit) #### unsafe fn [clone\_to\_uninit](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) (&self, dest: [\*mut](https://doc.rust-lang.org/stable/std/primitive.pointer.html) [u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) ) 🔬This is a nightly-only experimental API. (`clone_to_uninit` [#126799](https://github.com/rust-lang/rust/issues/126799) ) Performs copy-assignment from `self` to `dest`. [Read more](https://doc.rust-lang.org/stable/std/clone/trait.CloneToUninit.html#tymethod.clone_to_uninit) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#314) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-IntoIterator-for-I) ### impl [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") for I where I: [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html "trait std::iter::Iterator") , [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#315) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#associatedtype.Item-1) #### type [Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item) = ::[Item](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#associatedtype.Item "type std::iter::Iterator::Item") The type of the elements being iterated over. [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#316) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#associatedtype.IntoIter) #### type [IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter) = I Which kind of iterator are we turning this into? [Source](https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#319) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.into_iter) #### fn [into\_iter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) (self) -> I Creates an iterator from a value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#85-87) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-ToOwned-for-T) ### impl [ToOwned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html "trait std::borrow::ToOwned") for T where T: [Clone](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html "trait std::clone::Clone") , [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#89) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#associatedtype.Owned) #### type [Owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#associatedtype.Owned) = T The resulting type after obtaining ownership. [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#90) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.to_owned) #### fn [to\_owned](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) (&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#tymethod.to_owned) [Source](https://doc.rust-lang.org/stable/src/alloc/borrow.rs.html#94) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.clone_into) #### fn [clone\_into](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) (&self, target: [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) Uses borrowed data to replace owned data, usually by cloning. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.ToOwned.html#method.clone_into) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/str/struct.EncodeUtf16.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # Receiver in std::sync::mpsc - Rust [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#) --------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[sync](https://doc.rust-lang.org/stable/std/sync/index.html) ::[mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html) Struct Receiver Copy item path ============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#177-179) pub struct Receiver { /* private fields */ } Expand description The receiving half of Rust’s [`channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html "fn std::sync::mpsc::channel") (or [`sync_channel`](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.sync_channel.html "fn std::sync::mpsc::sync_channel") ) type. This half can only be owned by one thread. Messages sent to the channel can be retrieved using [`recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv "method std::sync::mpsc::Receiver::recv") . [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples) Examples ------------------------------------------------------------------------------------------ use std::sync::mpsc::channel; use std::thread; use std::time::Duration; let (send, recv) = channel(); thread::spawn(move || { send.send("Hello world!").unwrap(); thread::sleep(Duration::from_secs(2)); // block for two seconds send.send("Delayed for 2 seconds").unwrap(); }); println!("{}", recv.recv().unwrap()); // Received immediately println!("Waiting..."); println!("{}", recv.recv().unwrap()); // Received after 2 seconds [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc::channel;%0A++++use+std::thread;%0A++++use+std::time::Duration;%0A++++%0A++++let+(send,+recv)+=+channel();%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++send.send(%22Hello+world!%22).unwrap();%0A++++++++thread::sleep(Duration::from_secs(2));+//+block+for+two+seconds%0A++++++++send.send(%22Delayed+for+2+seconds%22).unwrap();%0A++++%7D);%0A++++%0A++++println!(%22%7B%7D%22,+recv.recv().unwrap());+//+Received+immediately%0A++++println!(%22Waiting...%22);%0A++++println!(%22%7B%7D%22,+recv.recv().unwrap());%0A%7D&edition=2024 "Run code") Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#implementations) -------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#764-1041) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Receiver%3CT%3E) ### impl [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#789-791) #### pub fn [try\_recv](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_recv) (&self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") Attempts to return a pending value on this receiver without blocking. This method will never block the caller in order to wait for data to become available. Instead, this will always return immediately with a possible option of pending data on the channel. This is useful for a flavor of “optimistic check” before deciding to block on a receiver. Compared with [`recv`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv "method std::sync::mpsc::Receiver::recv") , this function has two failure cases instead of one (one for disconnection, one for an empty buffer). ##### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples-1) Examples use std::sync::mpsc::{Receiver, channel}; let (_, receiver): (_, Receiver) = channel(); assert!(receiver.try_recv().is_err()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc::%7BReceiver,+channel%7D;%0A++++%0A++++let+(_,+receiver):+(_,+Receiver%3Ci32%3E)+=+channel();%0A++++%0A++++assert!(receiver.try_recv().is_err());%0A%7D&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#848-850) #### pub fn [recv](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv) (&self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") Attempts to wait for a value on this receiver, returning an error if the corresponding channel has hung up. This function will always block the current thread if there is no data available and it’s possible for more data to be sent (at least one sender still exists). Once a message is sent to the corresponding [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") (or [`SyncSender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html "struct std::sync::mpsc::SyncSender") ), this receiver will wake up and return that message. If the corresponding [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") has disconnected, or it disconnects while this call is blocking, this call will wake up and return [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") to indicate that no more messages can ever be received on this channel. However, since channels are buffered, messages sent before the disconnect will still be properly received. ##### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples-2) Examples use std::sync::mpsc; use std::thread; let (send, recv) = mpsc::channel(); let handle = thread::spawn(move || { send.send(1u8).unwrap(); }); handle.join().unwrap(); assert_eq!(Ok(1), recv.recv()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc;%0A++++use+std::thread;%0A++++%0A++++let+(send,+recv)+=+mpsc::channel();%0A++++let+handle+=+thread::spawn(move+%7C%7C+%7B%0A++++++++send.send(1u8).unwrap();%0A++++%7D);%0A++++%0A++++handle.join().unwrap();%0A++++%0A++++assert_eq!(Ok(1),+recv.recv());%0A%7D&edition=2024 "Run code") Buffering behavior: use std::sync::mpsc; use std::thread; use std::sync::mpsc::RecvError; let (send, recv) = mpsc::channel(); let handle = thread::spawn(move || { send.send(1u8).unwrap(); send.send(2).unwrap(); send.send(3).unwrap(); drop(send); }); // wait for the thread to join so we ensure the sender is dropped handle.join().unwrap(); assert_eq!(Ok(1), recv.recv()); assert_eq!(Ok(2), recv.recv()); assert_eq!(Ok(3), recv.recv()); assert_eq!(Err(RecvError), recv.recv()); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc;%0A++++use+std::thread;%0A++++use+std::sync::mpsc::RecvError;%0A++++%0A++++let+(send,+recv)+=+mpsc::channel();%0A++++let+handle+=+thread::spawn(move+%7C%7C+%7B%0A++++++++send.send(1u8).unwrap();%0A++++++++send.send(2).unwrap();%0A++++++++send.send(3).unwrap();%0A++++++++drop(send);%0A++++%7D);%0A++++%0A++++//+wait+for+the+thread+to+join+so+we+ensure+the+sender+is+dropped%0A++++handle.join().unwrap();%0A++++%0A++++assert_eq!(Ok(1),+recv.recv());%0A++++assert_eq!(Ok(2),+recv.recv());%0A++++assert_eq!(Ok(3),+recv.recv());%0A++++assert_eq!(Err(RecvError),+recv.recv());%0A%7D&edition=2024 "Run code") 1.12.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#908-910) #### pub fn [recv\_timeout](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv_timeout) (&self, timeout: [Duration](https://doc.rust-lang.org/stable/std/time/struct.Duration.html "struct std::time::Duration") ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") Attempts to wait for a value on this receiver, returning an error if the corresponding channel has hung up, or if it waits more than `timeout`. This function will always block the current thread if there is no data available and it’s possible for more data to be sent (at least one sender still exists). Once a message is sent to the corresponding [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") (or [`SyncSender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html "struct std::sync::mpsc::SyncSender") ), this receiver will wake up and return that message. If the corresponding [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") has disconnected, or it disconnects while this call is blocking, this call will wake up and return [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") to indicate that no more messages can ever be received on this channel. However, since channels are buffered, messages sent before the disconnect will still be properly received. ##### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples-3) Examples Successfully receiving value before encountering timeout: use std::thread; use std::time::Duration; use std::sync::mpsc; let (send, recv) = mpsc::channel(); thread::spawn(move || { send.send('a').unwrap(); }); assert_eq!( recv.recv_timeout(Duration::from_millis(400)), Ok('a') ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::time::Duration;%0A++++use+std::sync::mpsc;%0A++++%0A++++let+(send,+recv)+=+mpsc::channel();%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++send.send(%27a%27).unwrap();%0A++++%7D);%0A++++%0A++++assert_eq!(%0A++++++++recv.recv_timeout(Duration::from_millis(400)),%0A++++++++Ok(%27a%27)%0A++++);%0A%7D&edition=2024 "Run code") Receiving an error upon reaching timeout: use std::thread; use std::time::Duration; use std::sync::mpsc; let (send, recv) = mpsc::channel(); thread::spawn(move || { thread::sleep(Duration::from_millis(800)); send.send('a').unwrap(); }); assert_eq!( recv.recv_timeout(Duration::from_millis(400)), Err(mpsc::RecvTimeoutError::Timeout) ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::time::Duration;%0A++++use+std::sync::mpsc;%0A++++%0A++++let+(send,+recv)+=+mpsc::channel();%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++thread::sleep(Duration::from_millis(800));%0A++++++++send.send(%27a%27).unwrap();%0A++++%7D);%0A++++%0A++++assert_eq!(%0A++++++++recv.recv_timeout(Duration::from_millis(400)),%0A++++++++Err(mpsc::RecvTimeoutError::Timeout)%0A++++);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#969-971) #### pub fn [recv\_deadline](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.recv_deadline) (&self, deadline: [Instant](https://doc.rust-lang.org/stable/std/time/struct.Instant.html "struct std::time::Instant") ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") 🔬This is a nightly-only experimental API. (`deadline_api` [#46316](https://github.com/rust-lang/rust/issues/46316) ) Attempts to wait for a value on this receiver, returning an error if the corresponding channel has hung up, or if `deadline` is reached. This function will always block the current thread if there is no data available and it’s possible for more data to be sent. Once a message is sent to the corresponding [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") (or [`SyncSender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.SyncSender.html "struct std::sync::mpsc::SyncSender") ), then this receiver will wake up and return that message. If the corresponding [`Sender`](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Sender.html "struct std::sync::mpsc::Sender") has disconnected, or it disconnects while this call is blocking, this call will wake up and return [`Err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#variant.Err "variant std::result::Result::Err") to indicate that no more messages can ever be received on this channel. However, since channels are buffered, messages sent before the disconnect will still be properly received. ##### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples-4) Examples Successfully receiving value before reaching deadline: #![feature(deadline_api)] use std::thread; use std::time::{Duration, Instant}; use std::sync::mpsc; let (send, recv) = mpsc::channel(); thread::spawn(move || { send.send('a').unwrap(); }); assert_eq!( recv.recv_deadline(Instant::now() + Duration::from_millis(400)), Ok('a') ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(deadline_api)%5D%0A%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::time::%7BDuration,+Instant%7D;%0A++++use+std::sync::mpsc;%0A++++%0A++++let+(send,+recv)+=+mpsc::channel();%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++send.send(%27a%27).unwrap();%0A++++%7D);%0A++++%0A++++assert_eq!(%0A++++++++recv.recv_deadline(Instant::now()+%2B+Duration::from_millis(400)),%0A++++++++Ok(%27a%27)%0A++++);%0A%7D&version=nightly&edition=2024 "Run code") Receiving an error upon reaching deadline: #![feature(deadline_api)] use std::thread; use std::time::{Duration, Instant}; use std::sync::mpsc; let (send, recv) = mpsc::channel(); thread::spawn(move || { thread::sleep(Duration::from_millis(800)); send.send('a').unwrap(); }); assert_eq!( recv.recv_deadline(Instant::now() + Duration::from_millis(400)), Err(mpsc::RecvTimeoutError::Timeout) ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(deadline_api)%5D%0A%0Afn+main()+%7B%0A++++use+std::thread;%0A++++use+std::time::%7BDuration,+Instant%7D;%0A++++use+std::sync::mpsc;%0A++++%0A++++let+(send,+recv)+=+mpsc::channel();%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++thread::sleep(Duration::from_millis(800));%0A++++++++send.send(%27a%27).unwrap();%0A++++%7D);%0A++++%0A++++assert_eq!(%0A++++++++recv.recv_deadline(Instant::now()+%2B+Duration::from_millis(400)),%0A++++++++Err(mpsc::RecvTimeoutError::Timeout)%0A++++);%0A%7D&version=nightly&edition=2024 "Run code") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#997-999) #### pub fn [iter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.iter) (&self) -> [Iter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Iter.html "struct std::sync::mpsc::Iter") <'\_, T> [ⓘ](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#) Returns an iterator that will block waiting for messages, but never [`panic!`](https://doc.rust-lang.org/stable/std/macro.panic.html "macro std::panic") . It will return [`None`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None "variant std::option::Option::None") when the channel has hung up. ##### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples-5) Examples use std::sync::mpsc::channel; use std::thread; let (send, recv) = channel(); thread::spawn(move || { send.send(1).unwrap(); send.send(2).unwrap(); send.send(3).unwrap(); }); let mut iter = recv.iter(); assert_eq!(iter.next(), Some(1)); assert_eq!(iter.next(), Some(2)); assert_eq!(iter.next(), Some(3)); assert_eq!(iter.next(), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc::channel;%0A++++use+std::thread;%0A++++%0A++++let+(send,+recv)+=+channel();%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++send.send(1).unwrap();%0A++++++++send.send(2).unwrap();%0A++++++++send.send(3).unwrap();%0A++++%7D);%0A++++%0A++++let+mut+iter+=+recv.iter();%0A++++assert_eq!(iter.next(),+Some(1));%0A++++assert_eq!(iter.next(),+Some(2));%0A++++assert_eq!(iter.next(),+Some(3));%0A++++assert_eq!(iter.next(),+None);%0A%7D&edition=2024 "Run code") 1.15.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1038-1040) #### pub fn [try\_iter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_iter) (&self) -> [TryIter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.TryIter.html "struct std::sync::mpsc::TryIter") <'\_, T> [ⓘ](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#) Returns an iterator that will attempt to yield all pending values. It will return `None` if there are no more pending values or if the channel has hung up. The iterator will never [`panic!`](https://doc.rust-lang.org/stable/std/macro.panic.html "macro std::panic") or block the user by waiting for values. ##### [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#examples-6) Examples use std::sync::mpsc::channel; use std::thread; use std::time::Duration; let (sender, receiver) = channel(); // nothing is in the buffer yet assert!(receiver.try_iter().next().is_none()); thread::spawn(move || { thread::sleep(Duration::from_secs(1)); sender.send(1).unwrap(); sender.send(2).unwrap(); sender.send(3).unwrap(); }); // nothing is in the buffer yet assert!(receiver.try_iter().next().is_none()); // block for two seconds thread::sleep(Duration::from_secs(2)); let mut iter = receiver.try_iter(); assert_eq!(iter.next(), Some(1)); assert_eq!(iter.next(), Some(2)); assert_eq!(iter.next(), Some(3)); assert_eq!(iter.next(), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::sync::mpsc::channel;%0A++++use+std::thread;%0A++++use+std::time::Duration;%0A++++%0A++++let+(sender,+receiver)+=+channel();%0A++++%0A++++//+nothing+is+in+the+buffer+yet%0A++++assert!(receiver.try_iter().next().is_none());%0A++++%0A++++thread::spawn(move+%7C%7C+%7B%0A++++++++thread::sleep(Duration::from_secs(1));%0A++++++++sender.send(1).unwrap();%0A++++++++sender.send(2).unwrap();%0A++++++++sender.send(3).unwrap();%0A++++%7D);%0A++++%0A++++//+nothing+is+in+the+buffer+yet%0A++++assert!(receiver.try_iter().next().is_none());%0A++++%0A++++//+block+for+two+seconds%0A++++thread::sleep(Duration::from_secs(2));%0A++++%0A++++let+mut+iter+=+receiver.try_iter();%0A++++assert_eq!(iter.next(),+Some(1));%0A++++assert_eq!(iter.next(),+Some(2));%0A++++assert_eq!(iter.next(),+Some(3));%0A++++assert_eq!(iter.next(),+None);%0A%7D&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#trait-implementations) -------------------------------------------------------------------------------------------------------------------- 1.8.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1090-1094) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Debug-for-Receiver%3CT%3E) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1091-1093) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) 1.1.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1062-1069) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-IntoIterator-for-%26Receiver%3CT%3E) ### impl<'a, T> [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") for &'a [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1063) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#associatedtype.Item) #### type [Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item) = T The type of the elements being iterated over. [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1064) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#associatedtype.IntoIter) #### type [IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter) = [Iter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Iter.html "struct std::sync::mpsc::Iter") <'a, T> Which kind of iterator are we turning this into? [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1066-1068) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.into_iter) #### fn [into\_iter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) (self) -> [Iter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Iter.html "struct std::sync::mpsc::Iter") <'a, T> [ⓘ](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#) Creates an iterator from a value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) 1.1.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1080-1087) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-IntoIterator-for-Receiver%3CT%3E) ### impl [IntoIterator](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html "trait std::iter::IntoIterator") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1081) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#associatedtype.Item-1) #### type [Item](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.Item) = T The type of the elements being iterated over. [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1082) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#associatedtype.IntoIter-1) #### type [IntoIter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#associatedtype.IntoIter) = [IntoIter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.IntoIter.html "struct std::sync::mpsc::IntoIter") Which kind of iterator are we turning this into? [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#1084-1086) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.into_iter-1) #### fn [into\_iter](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) (self) -> [IntoIter](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.IntoIter.html "struct std::sync::mpsc::IntoIter") [ⓘ](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#) Creates an iterator from a value. [Read more](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter) 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#184) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Send-for-Receiver%3CT%3E) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/sync/mpsc.rs.html#187) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Sync-for-Receiver%3CT%3E) ### impl ![Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#synthetic-implementations) ----------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Freeze-for-Receiver%3CT%3E) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-RefUnwindSafe-for-Receiver%3CT%3E) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Unpin-for-Receiver%3CT%3E) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-UnwindSafe-for-Receiver%3CT%3E) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [Receiver](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html "struct std::sync::mpsc::Receiver") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#blanket-implementations) ------------------------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. ---

::[Target](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html#associatedtype.Target "type std::ops::Deref::Target") as [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") \>::[Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output "type std::future::Future::Output") [Source](https://doc.rust-lang.org/stable/src/core/sync/exclusive.rs.html#216-218) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-Exclusive%3CT%3E) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [Exclusive](https://doc.rust-lang.org/stable/std/sync/struct.Exclusive.html "struct std::sync::Exclusive") where T: [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/sync/exclusive.rs.html#220) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-5) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = ::[Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output "type std::future::Future::Output") 1.48.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/pending.rs.html#38) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-Pending%3CT%3E) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [Pending](https://doc.rust-lang.org/stable/std/future/struct.Pending.html "struct std::future::Pending") [Source](https://doc.rust-lang.org/stable/src/core/future/pending.rs.html#39) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-6) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = T 1.48.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/ready.rs.html#18) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-Ready%3CT%3E) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [Ready](https://doc.rust-lang.org/stable/std/future/struct.Ready.html "struct std::future::Ready") [Source](https://doc.rust-lang.org/stable/src/core/future/ready.rs.html#19) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-7) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = T 1.64.0 · [Source](https://doc.rust-lang.org/stable/src/core/future/poll_fn.rs.html#143-145) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#impl-Future-for-PollFn%3CF%3E) ### impl [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html "trait std::future::Future") for [PollFn](https://doc.rust-lang.org/stable/std/future/struct.PollFn.html "struct std::future::PollFn") where F: [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") (&mut [Context](https://doc.rust-lang.org/stable/std/task/struct.Context.html "struct std::task::Context") <'\_>) -> [Poll](https://doc.rust-lang.org/stable/std/task/enum.Poll.html "enum std::task::Poll") , [Source](https://doc.rust-lang.org/stable/src/core/future/poll_fn.rs.html#147) [§](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output-8) #### type [Output](https://doc.rust-lang.org/stable/std/future/trait.Future.html#associatedtype.Output) = T --- # LocalKey in std::thread - Rust [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#) ------------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) ::[thread](https://doc.rust-lang.org/stable/std/thread/index.html) Struct LocalKey Copy item path ============================== 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#110-126) pub struct LocalKey { /* private fields */ } Expand description A thread local storage (TLS) key which owns its contents. This key uses the fastest implementation available on the target platform. It is instantiated with the [`thread_local!`](https://doc.rust-lang.org/stable/std/macro.thread_local.html "macro std::thread_local") macro and the primary method is the [`with`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with "method std::thread::LocalKey::with") method, though there are helpers to make working with [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") types easier. The [`with`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with "method std::thread::LocalKey::with") method yields a reference to the contained value which cannot outlive the current thread or escape the given closure. [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#initialization-and-destruction) Initialization and Destruction ----------------------------------------------------------------------------------------------------------------------------------- Initialization is dynamically performed on the first call to a setter (e.g. [`with`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with "method std::thread::LocalKey::with") ) within a thread, and values that implement [`Drop`](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") get destructed when a thread exits. Some platform-specific caveats apply, which are explained below. Note that if the destructor panics, the whole process will be [aborted](https://doc.rust-lang.org/stable/std/process/fn.abort.html "fn std::process::abort") . A `LocalKey`’s initializer cannot recursively depend on itself. Using a `LocalKey` in this way may cause panics, aborts, or infinite recursion on the first call to `with`. [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#single-thread-synchronization) Single-thread Synchronization --------------------------------------------------------------------------------------------------------------------------------- Though there is no potential race with other threads, it is still possible to obtain multiple references to the thread-local data in different places on the call stack. For this reason, only shared (`&T`) references may be obtained. To allow obtaining an exclusive mutable reference (`&mut T`), typically a [`Cell`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") or [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") is used (see the [`std::cell`](https://doc.rust-lang.org/stable/std/cell/index.html "mod std::cell") for more information on how exactly this works). To make this easier there are specialized implementations for [`LocalKey>`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-LocalKey%3CCell%3CT%3E%3E) and [`LocalKey>`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-LocalKey%3CRefCell%3CT%3E%3E) . [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples) Examples --------------------------------------------------------------------------------------- use std::cell::Cell; use std::thread; // explicit `const {}` block enables more efficient initialization thread_local!(static FOO: Cell = const { Cell::new(1) }); assert_eq!(FOO.get(), 1); FOO.set(2); // each thread starts out with the initial value of 1 let t = thread::spawn(move || { assert_eq!(FOO.get(), 1); FOO.set(3); }); // wait for the thread to complete and bail out on panic t.join().unwrap(); // we retain our original value of 2 despite the child thread assert_eq!(FOO.get(), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++use+std::thread;%0A++++%0A++++//+explicit+%60const+%7B%7D%60+block+enables+more+efficient+initialization%0A++++thread_local!(static+FOO:+Cell%3Cu32%3E+=+const+%7B+Cell::new(1)+%7D);%0A++++%0A++++assert_eq!(FOO.get(),+1);%0A++++FOO.set(2);%0A++++%0A++++//+each+thread+starts+out+with+the+initial+value+of+1%0A++++let+t+=+thread::spawn(move+%7C%7C+%7B%0A++++++++assert_eq!(FOO.get(),+1);%0A++++++++FOO.set(3);%0A++++%7D);%0A++++%0A++++//+wait+for+the+thread+to+complete+and+bail+out+on+panic%0A++++t.join().unwrap();%0A++++%0A++++//+we+retain+our+original+value+of+2+despite+the+child+thread%0A++++assert_eq!(FOO.get(),+2);%0A%7D&edition=2024 "Run code") [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#platform-specific-behavior) Platform-specific behavior --------------------------------------------------------------------------------------------------------------------------- Note that a “best effort” is made to ensure that destructors for types stored in thread local storage are run, but not all platforms can guarantee that destructors will be run for all types in thread local storage. For example, there are a number of known caveats where destructors are not run: 1. On Unix systems when pthread-based TLS is being used, destructors will not be run for TLS values on the main thread when it exits. Note that the application will exit immediately after the main thread exits as well. 2. On all platforms it’s possible for TLS to re-initialize other TLS slots during destruction. Some platforms ensure that this cannot happen infinitely by preventing re-initialization of any slot that has been destroyed, but not all platforms have this guard. Those platforms that do not guard typically have a synthetic limit after which point no more destructors are run. 3. When the process exits on Windows systems, TLS destructors may only be run on the thread that causes the process to exit. This is because the other threads may be forcibly terminated. ### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#synchronization-in-thread-local-destructors) Synchronization in thread-local destructors On Windows, synchronization operations (such as [`JoinHandle::join`](https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join "method std::thread::JoinHandle::join") ) in thread local destructors are prone to deadlocks and so should be avoided. This is because the [loader lock](https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices) is held while a destructor is run. The lock is acquired whenever a thread starts or exits or when a DLL is loaded or unloaded. Therefore these events are blocked for as long as a thread local destructor is running. Implementations[§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#implementations) ----------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#433-538) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-LocalKey%3CT%3E) ### impl [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#468-476) #### pub fn [with](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with) (&'static self, f: F) -> R where F: [FnOnce](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") ([&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> R, Acquires a reference to the value in this TLS key. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics) Panics This function will `panic!()` if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-1) Examples thread_local! { pub static STATIC: String = String::from("I am"); } assert_eq!( STATIC.with(|original_value| format!("{original_value} initialized")), "I am initialized", ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++thread_local!+%7B%0A++++++++pub+static+STATIC:+String+=+String::from(%22I+am%22);%0A++++%7D%0A++++%0A++++assert_eq!(%0A++++++++STATIC.with(%7Coriginal_value%7C+format!(%22%7Boriginal_value%7D+initialized%22)),%0A++++++++%22I+am+initialized%22,%0A++++);%0A%7D&edition=2024 "Run code") 1.26.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#503-509) #### pub fn [try\_with](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.try_with) (&'static self, f: F) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") where F: [FnOnce](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") ([&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> R, Acquires a reference to the value in this TLS key. This will lazily initialize the value if this thread has not referenced this key yet. If the key has been destroyed (which may happen if this is called in a destructor), this function will return an [`AccessError`](https://doc.rust-lang.org/stable/std/thread/struct.AccessError.html "struct std::thread::AccessError") . ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-1) Panics This function will still `panic!()` if the key is uninitialized and the key’s initializer panics. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-2) Examples thread_local! { pub static STATIC: String = String::from("I am"); } assert_eq!( STATIC.try_with(|original_value| format!("{original_value} initialized")), Ok(String::from("I am initialized")), ); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++thread_local!+%7B%0A++++++++pub+static+STATIC:+String+=+String::from(%22I+am%22);%0A++++%7D%0A++++%0A++++assert_eq!(%0A++++++++STATIC.try_with(%7Coriginal_value%7C+format!(%22%7Boriginal_value%7D+initialized%22)),%0A++++++++Ok(String::from(%22I+am+initialized%22)),%0A++++);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#540-688) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-LocalKey%3CCell%3CT%3E%3E) ### impl [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") <[Cell](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html "struct std::cell::Cell") > 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#568-577) #### pub fn [set](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.set) (&'static self, value: T) Sets or initializes the contained value. Unlike the other methods, this will _not_ run the lazy initializer of the thread local. Instead, it will be directly initialized with the given value if it wasn’t initialized yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-2) Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-3) Examples use std::cell::Cell; thread_local! { static X: Cell = panic!("!"); } // Calling X.get() here would result in a panic. X.set(123); // But X.set() is fine, as it skips the initializer above. assert_eq!(X.get(), 123); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+Cell%3Ci32%3E+=+panic!(%22!%22);%0A++++%7D%0A++++%0A++++//+Calling+X.get()+here+would+result+in+a+panic.%0A++++%0A++++X.set(123);+//+But+X.set()+is+fine,+as+it+skips+the+initializer+above.%0A++++%0A++++assert_eq!(X.get(),+123);%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#601-606) #### pub fn [get](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.get) (&'static self) -> T where T: [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , Returns a copy of the contained value. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-3) Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-4) Examples use std::cell::Cell; thread_local! { static X: Cell = const { Cell::new(1) }; } assert_eq!(X.get(), 1); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+Cell%3Ci32%3E+=+const+%7B+Cell::new(1)+%7D;%0A++++%7D%0A++++%0A++++assert_eq!(X.get(),+1);%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#631-636) #### pub fn [take](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.take) (&'static self) -> T where T: [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") , Takes the contained value, leaving `Default::default()` in its place. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-4) Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-5) Examples use std::cell::Cell; thread_local! { static X: Cell> = const { Cell::new(Some(1)) }; } assert_eq!(X.take(), Some(1)); assert_eq!(X.take(), None); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+Cell%3COption%3Ci32%3E%3E+=+const+%7B+Cell::new(Some(1))+%7D;%0A++++%7D%0A++++%0A++++assert_eq!(X.take(),+Some(1));%0A++++assert_eq!(X.take(),+None);%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#662-664) #### pub fn [replace](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.replace) (&'static self, value: T) -> T Replaces the contained value, returning the old value. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-5) Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-6) Examples use std::cell::Cell; thread_local! { static X: Cell = const { Cell::new(1) }; } assert_eq!(X.replace(2), 1); assert_eq!(X.replace(3), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+Cell%3Ci32%3E+=+const+%7B+Cell::new(1)+%7D;%0A++++%7D%0A++++%0A++++assert_eq!(X.replace(2),+1);%0A++++assert_eq!(X.replace(3),+2);%0A%7D&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#682-687) #### pub fn [update](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.update) (&'static self, f: impl [FnOnce](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") (T) -> T) where T: [Copy](https://doc.rust-lang.org/stable/std/marker/trait.Copy.html "trait std::marker::Copy") , 🔬This is a nightly-only experimental API. (`local_key_cell_update` [#143989](https://github.com/rust-lang/rust/issues/143989) ) Updates the contained value using a function. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-7) Examples #![feature(local_key_cell_update)] use std::cell::Cell; thread_local! { static X: Cell = const { Cell::new(5) }; } X.update(|x| x + 1); assert_eq!(X.get(), 6); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A%23!%5Bfeature(local_key_cell_update)%5D%0A%0Afn+main()+%7B%0A++++use+std::cell::Cell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+Cell%3Ci32%3E+=+const+%7B+Cell::new(5)+%7D;%0A++++%7D%0A++++%0A++++X.update(%7Cx%7C+x+%2B+1);%0A++++assert_eq!(X.get(),+6);%0A%7D&version=nightly&edition=2024 "Run code") [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#690-860) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-LocalKey%3CRefCell%3CT%3E%3E) ### impl [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") <[RefCell](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html "struct std::cell::RefCell") > 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#715-720) #### pub fn [with\_borrow](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with_borrow) (&'static self, f: F) -> R where F: [FnOnce](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") ([&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> R, Acquires a reference to the contained value. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-6) Panics Panics if the value is currently mutably borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-8) Examples use std::cell::RefCell; thread_local! { static X: RefCell> = RefCell::new(Vec::new()); } X.with_borrow(|v| assert!(v.is_empty())); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+RefCell%3CVec%3Ci32%3E%3E+=+RefCell::new(Vec::new());%0A++++%7D%0A++++%0A++++X.with_borrow(%7Cv%7C+assert!(v.is_empty()));%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#748-753) #### pub fn [with\_borrow\_mut](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.with_borrow_mut) (&'static self, f: F) -> R where F: [FnOnce](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") ([&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) ) -> R, Acquires a mutable reference to the contained value. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-7) Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-9) Examples use std::cell::RefCell; thread_local! { static X: RefCell> = RefCell::new(Vec::new()); } X.with_borrow_mut(|v| v.push(1)); X.with_borrow(|v| assert_eq!(*v, vec![1])); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+RefCell%3CVec%3Ci32%3E%3E+=+RefCell::new(Vec::new());%0A++++%7D%0A++++%0A++++X.with_borrow_mut(%7Cv%7C+v.push(1));%0A++++%0A++++X.with_borrow(%7Cv%7C+assert_eq!(*v,+vec!%5B1%5D));%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#784-793) #### pub fn [set](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.set-1) (&'static self, value: T) Sets or initializes the contained value. Unlike the other methods, this will _not_ run the lazy initializer of the thread local. Instead, it will be directly initialized with the given value if it wasn’t initialized yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-8) Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-10) Examples use std::cell::RefCell; thread_local! { static X: RefCell> = panic!("!"); } // Calling X.with() here would result in a panic. X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above. X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3])); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+RefCell%3CVec%3Ci32%3E%3E+=+panic!(%22!%22);%0A++++%7D%0A++++%0A++++//+Calling+X.with()+here+would+result+in+a+panic.%0A++++%0A++++X.set(vec!%5B1,+2,+3%5D);+//+But+X.set()+is+fine,+as+it+skips+the+initializer+above.%0A++++%0A++++X.with_borrow(%7Cv%7C+assert_eq!(*v,+vec!%5B1,+2,+3%5D));%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#825-830) #### pub fn [take](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.take-1) (&'static self) -> T where T: [Default](https://doc.rust-lang.org/stable/std/default/trait.Default.html "trait std::default::Default") , Takes the contained value, leaving `Default::default()` in its place. This will lazily initialize the value if this thread has not referenced this key yet. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-9) Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-11) Examples use std::cell::RefCell; thread_local! { static X: RefCell> = RefCell::new(Vec::new()); } X.with_borrow_mut(|v| v.push(1)); let a = X.take(); assert_eq!(a, vec![1]); X.with_borrow(|v| assert!(v.is_empty())); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+RefCell%3CVec%3Ci32%3E%3E+=+RefCell::new(Vec::new());%0A++++%7D%0A++++%0A++++X.with_borrow_mut(%7Cv%7C+v.push(1));%0A++++%0A++++let+a+=+X.take();%0A++++%0A++++assert_eq!(a,+vec!%5B1%5D);%0A++++%0A++++X.with_borrow(%7Cv%7C+assert!(v.is_empty()));%0A%7D&edition=2024 "Run code") 1.73.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#857-859) #### pub fn [replace](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.replace-1) (&'static self, value: T) -> T Replaces the contained value, returning the old value. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#panics-10) Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#examples-12) Examples use std::cell::RefCell; thread_local! { static X: RefCell> = RefCell::new(Vec::new()); } let prev = X.replace(vec![1, 2, 3]); assert!(prev.is_empty()); X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3])); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::cell::RefCell;%0A++++%0A++++thread_local!+%7B%0A++++++++static+X:+RefCell%3CVec%3Ci32%3E%3E+=+RefCell::new(Vec::new());%0A++++%7D%0A++++%0A++++let+prev+=+X.replace(vec!%5B1,+2,+3%5D);%0A++++assert!(prev.is_empty());%0A++++%0A++++X.with_borrow(%7Cv%7C+assert_eq!(*v,+vec!%5B1,+2,+3%5D));%0A%7D&edition=2024 "Run code") Trait Implementations[§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#trait-implementations) ----------------------------------------------------------------------------------------------------------------- 1.16.0 · [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#129-133) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Debug-for-LocalKey%3CT%3E) ### impl [Debug](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html "trait std::fmt::Debug") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") [Source](https://doc.rust-lang.org/stable/src/std/thread/local.rs.html#130-132) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.fmt) #### fn [fmt](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [Formatter](https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html "struct std::fmt::Formatter") <'\_>) -> [Result](https://doc.rust-lang.org/stable/std/fmt/type.Result.html "type std::fmt::Result") Formats the value using the given formatter. [Read more](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#tymethod.fmt) Auto Trait Implementations[§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#synthetic-implementations) -------------------------------------------------------------------------------------------------------------------------- [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Freeze-for-LocalKey%3CT%3E) ### impl [Freeze](https://doc.rust-lang.org/stable/std/marker/trait.Freeze.html "trait std::marker::Freeze") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-RefUnwindSafe-for-LocalKey%3CT%3E) ### impl [RefUnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Send-for-LocalKey%3CT%3E) ### impl [Send](https://doc.rust-lang.org/stable/std/marker/trait.Send.html "trait std::marker::Send") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Sync-for-LocalKey%3CT%3E) ### impl [Sync](https://doc.rust-lang.org/stable/std/marker/trait.Sync.html "trait std::marker::Sync") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Unpin-for-LocalKey%3CT%3E) ### impl [Unpin](https://doc.rust-lang.org/stable/std/marker/trait.Unpin.html "trait std::marker::Unpin") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-UnwindSafe-for-LocalKey%3CT%3E) ### impl [UnwindSafe](https://doc.rust-lang.org/stable/std/panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") for [LocalKey](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html "struct std::thread::LocalKey") Blanket Implementations[§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#blanket-implementations) --------------------------------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#138) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Any-for-T) ### impl [Any](https://doc.rust-lang.org/stable/std/any/trait.Any.html "trait std::any::Any") for T where T: 'static + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/any.rs.html#139) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.type_id) #### fn [type\_id](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) (&self) -> [TypeId](https://doc.rust-lang.org/stable/std/any/struct.TypeId.html "struct std::any::TypeId") Gets the `TypeId` of `self`. [Read more](https://doc.rust-lang.org/stable/std/any/trait.Any.html#tymethod.type_id) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#212) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Borrow%3CT%3E-for-T) ### impl [Borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html "trait std::borrow::Borrow") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#214) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.borrow) #### fn [borrow](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [&T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Immutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#tymethod.borrow) [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#221) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-BorrowMut%3CT%3E-for-T) ### impl [BorrowMut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html "trait std::borrow::BorrowMut") for T where T: ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , [Source](https://doc.rust-lang.org/stable/src/core/borrow.rs.html#222) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.borrow_mut) #### fn [borrow\_mut](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) (&mut self) -> [&mut T](https://doc.rust-lang.org/stable/std/primitive.reference.html) Mutably borrows from an owned value. [Read more](https://doc.rust-lang.org/stable/std/borrow/trait.BorrowMut.html#tymethod.borrow_mut) [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#785) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-From%3CT%3E-for-T) ### impl [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for T [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#788) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.from) #### fn [from](https://doc.rust-lang.org/stable/std/convert/trait.From.html#tymethod.from) (t: T) -> T Returns the argument unchanged. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#767-769) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-Into%3CU%3E-for-T) ### impl [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") for T where U: [From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#777) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.into) #### fn [into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html#tymethod.into) (self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](https://doc.rust-lang.org/stable/std/convert/trait.From.html "trait std::convert::From") for U` chooses to do. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#827-829) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-TryFrom%3CU%3E-for-T) ### impl [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") for T where U: [Into](https://doc.rust-lang.org/stable/std/convert/trait.Into.html "trait std::convert::Into") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#831) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#associatedtype.Error-1) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error) = [Infallible](https://doc.rust-lang.org/stable/std/convert/enum.Infallible.html "enum std::convert::Infallible") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#834) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.try_from) #### fn [try\_from](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#tymethod.try_from) (value: U) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#811-813) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#impl-TryInto%3CU%3E-for-T) ### impl [TryInto](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html "trait std::convert::TryInto") for T where U: [TryFrom](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html "trait std::convert::TryFrom") , [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#815) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#associatedtype.Error) #### type [Error](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#associatedtype.Error) = >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") The type returned in the event of a conversion error. [Source](https://doc.rust-lang.org/stable/src/core/convert/mod.rs.html#818) [§](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.try_into) #### fn [try\_into](https://doc.rust-lang.org/stable/std/convert/trait.TryInto.html#tymethod.try_into) (self) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") >::[Error](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html#associatedtype.Error "type std::convert::TryFrom::Error") \> Performs the conversion. --- # std::ops - Rust [Module ops](https://doc.rust-lang.org/stable/std/ops/index.html#) ------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) Module ops Copy item path ========================= 1.0.0 · [Source](https://doc.rust-lang.org/stable/src/core/lib.rs.html#297) Expand description Overloadable operators. Implementing these traits allows you to overload certain operators. Some of these traits are imported by the prelude, so they are available in every Rust program. Only operators backed by traits can be overloaded. For example, the addition operator (`+`) can be overloaded through the [`Add`](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") trait, but since the assignment operator (`=`) has no backing trait, there is no way of overloading its semantics. Additionally, this module does not provide any mechanism to create new operators. If traitless overloading or custom operators are required, you should look toward macros to extend Rust’s syntax. Implementations of operator traits should be unsurprising in their respective contexts, keeping in mind their usual meanings and [operator precedence](https://doc.rust-lang.org/stable/reference/expressions.html#expression-precedence) . For example, when implementing [`Mul`](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html "trait std::ops::Mul") , the operation should have some resemblance to multiplication (and share expected properties like associativity). Note that the `&&` and `||` operators are currently not supported for overloading. Due to their short circuiting nature, they require a different design from traits for other operators like [`BitAnd`](https://doc.rust-lang.org/stable/std/ops/trait.BitAnd.html "trait std::ops::BitAnd") . Designs for them are under discussion. Many of the operators take their operands by value. In non-generic contexts involving built-in types, this is usually not a problem. However, using these operators in generic code, requires some attention if values have to be reused as opposed to letting the operators consume them. One option is to occasionally use [`clone`](https://doc.rust-lang.org/stable/std/clone/trait.Clone.html#tymethod.clone "method std::clone::Clone::clone") . Another option is to rely on the types involved providing additional operator implementations for references. For example, for a user-defined type `T` which is supposed to support addition, it is probably a good idea to have both `T` and `&T` implement the traits [`Add`](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") and [`Add<&T>`](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") so that generic code can be written without unnecessary cloning. [§](https://doc.rust-lang.org/stable/std/ops/index.html#examples) Examples -------------------------------------------------------------------------- This example creates a `Point` struct that implements [`Add`](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") and [`Sub`](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html "trait std::ops::Sub") , and then demonstrates adding and subtracting two `Point`s. use std::ops::{Add, Sub}; #[derive(Debug, Copy, Clone, PartialEq)] struct Point { x: i32, y: i32, } impl Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Self {x: self.x + other.x, y: self.y + other.y} } } impl Sub for Point { type Output = Self; fn sub(self, other: Self) -> Self { Self {x: self.x - other.x, y: self.y - other.y} } } assert_eq!(Point {x: 3, y: 3}, Point {x: 1, y: 0} + Point {x: 2, y: 3}); assert_eq!(Point {x: -1, y: -3}, Point {x: 1, y: 0} - Point {x: 2, y: 3}); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++use+std::ops::%7BAdd,+Sub%7D;%0A++++%0A++++%23%5Bderive(Debug,+Copy,+Clone,+PartialEq)%5D%0A++++struct+Point+%7B%0A++++++++x:+i32,%0A++++++++y:+i32,%0A++++%7D%0A++++%0A++++impl+Add+for+Point+%7B%0A++++++++type+Output+=+Self;%0A++++%0A++++++++fn+add(self,+other:+Self)+-%3E+Self+%7B%0A++++++++++++Self+%7Bx:+self.x+%2B+other.x,+y:+self.y+%2B+other.y%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++impl+Sub+for+Point+%7B%0A++++++++type+Output+=+Self;%0A++++%0A++++++++fn+sub(self,+other:+Self)+-%3E+Self+%7B%0A++++++++++++Self+%7Bx:+self.x+-+other.x,+y:+self.y+-+other.y%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++assert_eq!(Point+%7Bx:+3,+y:+3%7D,+Point+%7Bx:+1,+y:+0%7D+%2B+Point+%7Bx:+2,+y:+3%7D);%0A++++assert_eq!(Point+%7Bx:+-1,+y:+-3%7D,+Point+%7Bx:+1,+y:+0%7D+-+Point+%7Bx:+2,+y:+3%7D);%0A%7D&edition=2024 "Run code") See the documentation for each trait for an example implementation. The [`Fn`](https://doc.rust-lang.org/stable/std/ops/trait.Fn.html "trait std::ops::Fn") , [`FnMut`](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") , and [`FnOnce`](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") traits are implemented by types that can be invoked like functions. Note that [`Fn`](https://doc.rust-lang.org/stable/std/ops/trait.Fn.html "trait std::ops::Fn") takes `&self`, [`FnMut`](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") takes `&mut self` and [`FnOnce`](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") takes `self`. These correspond to the three kinds of methods that can be invoked on an instance: call-by-reference, call-by-mutable-reference, and call-by-value. The most common use of these traits is to act as bounds to higher-level functions that take functions or closures as arguments. Taking a [`Fn`](https://doc.rust-lang.org/stable/std/ops/trait.Fn.html "trait std::ops::Fn") as a parameter: fn call_with_one(func: F) -> usize where F: Fn(usize) -> usize { func(1) } let double = |x| x * 2; assert_eq!(call_with_one(double), 2); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+call_with_one%3CF%3E(func:+F)+-%3E+usize%0A++++++++where+F:+Fn(usize)+-%3E+usize%0A++++%7B%0A++++++++func(1)%0A++++%7D%0A++++%0A++++let+double+=+%7Cx%7C+x+*+2;%0A++++assert_eq!(call_with_one(double),+2);%0A%7D&edition=2024 "Run code") Taking a [`FnMut`](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") as a parameter: fn do_twice(mut func: F) where F: FnMut() { func(); func(); } let mut x: usize = 1; { let add_two_to_x = || x += 2; do_twice(add_two_to_x); } assert_eq!(x, 5); [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+do_twice%3CF%3E(mut+func:+F)%0A++++++++where+F:+FnMut()%0A++++%7B%0A++++++++func();%0A++++++++func();%0A++++%7D%0A++++%0A++++let+mut+x:+usize+=+1;%0A++++%7B%0A++++++++let+add_two_to_x+=+%7C%7C+x+%2B=+2;%0A++++++++do_twice(add_two_to_x);%0A++++%7D%0A++++%0A++++assert_eq!(x,+5);%0A%7D&edition=2024 "Run code") Taking a [`FnOnce`](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") as a parameter: fn consume_with_relish(func: F) where F: FnOnce() -> String { // `func` consumes its captured variables, so it cannot be run more // than once println!("Consumed: {}", func()); println!("Delicious!"); // Attempting to invoke `func()` again will throw a `use of moved // value` error for `func` } let x = String::from("x"); let consume_and_return_x = move || x; consume_with_relish(consume_and_return_x); // `consume_and_return_x` can no longer be invoked at this point [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn+main()+%7B%0A++++fn+consume_with_relish%3CF%3E(func:+F)%0A++++++++where+F:+FnOnce()+-%3E+String%0A++++%7B%0A++++++++//+%60func%60+consumes+its+captured+variables,+so+it+cannot+be+run+more%0A++++++++//+than+once%0A++++++++println!(%22Consumed:+%7B%7D%22,+func());%0A++++%0A++++++++println!(%22Delicious!%22);%0A++++%0A++++++++//+Attempting+to+invoke+%60func()%60+again+will+throw+a+%60use+of+moved%0A++++++++//+value%60+error+for+%60func%60%0A++++%7D%0A++++%0A++++let+x+=+String::from(%22x%22);%0A++++let+consume_and_return_x+=+move+%7C%7C+x;%0A++++consume_with_relish(consume_and_return_x);%0A%7D&edition=2024 "Run code") Structs[§](https://doc.rust-lang.org/stable/std/ops/index.html#structs) ------------------------------------------------------------------------ [Range](https://doc.rust-lang.org/stable/std/ops/struct.Range.html "struct std::ops::Range") A (half-open) range bounded inclusively below and exclusively above (`start..end`). [RangeFrom](https://doc.rust-lang.org/stable/std/ops/struct.RangeFrom.html "struct std::ops::RangeFrom") A range only bounded inclusively below (`start..`). [RangeFull](https://doc.rust-lang.org/stable/std/ops/struct.RangeFull.html "struct std::ops::RangeFull") An unbounded range (`..`). [RangeInclusive](https://doc.rust-lang.org/stable/std/ops/struct.RangeInclusive.html "struct std::ops::RangeInclusive") A range bounded inclusively below and above (`start..=end`). [RangeTo](https://doc.rust-lang.org/stable/std/ops/struct.RangeTo.html "struct std::ops::RangeTo") A range only bounded exclusively above (`..end`). [RangeToInclusive](https://doc.rust-lang.org/stable/std/ops/struct.RangeToInclusive.html "struct std::ops::RangeToInclusive") A range only bounded inclusively above (`..=end`). [Yeet](https://doc.rust-lang.org/stable/std/ops/struct.Yeet.html "struct std::ops::Yeet") Experimental Implement `FromResidual>` on your type to enable `do yeet expr` syntax in functions returning your type. Enums[§](https://doc.rust-lang.org/stable/std/ops/index.html#enums) -------------------------------------------------------------------- [Bound](https://doc.rust-lang.org/stable/std/ops/enum.Bound.html "enum std::ops::Bound") An endpoint of a range of keys. [ControlFlow](https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html "enum std::ops::ControlFlow") Used to tell an operation whether it should exit early or go on as usual. [CoroutineState](https://doc.rust-lang.org/stable/std/ops/enum.CoroutineState.html "enum std::ops::CoroutineState") Experimental The result of a coroutine resumption. [OneSidedRangeBound](https://doc.rust-lang.org/stable/std/ops/enum.OneSidedRangeBound.html "enum std::ops::OneSidedRangeBound") Experimental An internal helper for `split_off` functions indicating which end a `OneSidedRange` is bounded on. Traits[§](https://doc.rust-lang.org/stable/std/ops/index.html#traits) ---------------------------------------------------------------------- [Add](https://doc.rust-lang.org/stable/std/ops/trait.Add.html "trait std::ops::Add") The addition operator `+`. [AddAssign](https://doc.rust-lang.org/stable/std/ops/trait.AddAssign.html "trait std::ops::AddAssign") The addition assignment operator `+=`. [AsyncFn](https://doc.rust-lang.org/stable/std/ops/trait.AsyncFn.html "trait std::ops::AsyncFn") An async-aware version of the [`Fn`](https://doc.rust-lang.org/stable/std/ops/trait.Fn.html "trait std::ops::Fn") trait. [AsyncFnMut](https://doc.rust-lang.org/stable/std/ops/trait.AsyncFnMut.html "trait std::ops::AsyncFnMut") An async-aware version of the [`FnMut`](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") trait. [AsyncFnOnce](https://doc.rust-lang.org/stable/std/ops/trait.AsyncFnOnce.html "trait std::ops::AsyncFnOnce") An async-aware version of the [`FnOnce`](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") trait. [BitAnd](https://doc.rust-lang.org/stable/std/ops/trait.BitAnd.html "trait std::ops::BitAnd") The bitwise AND operator `&`. [BitAndAssign](https://doc.rust-lang.org/stable/std/ops/trait.BitAndAssign.html "trait std::ops::BitAndAssign") The bitwise AND assignment operator `&=`. [BitOr](https://doc.rust-lang.org/stable/std/ops/trait.BitOr.html "trait std::ops::BitOr") The bitwise OR operator `|`. [BitOrAssign](https://doc.rust-lang.org/stable/std/ops/trait.BitOrAssign.html "trait std::ops::BitOrAssign") The bitwise OR assignment operator `|=`. [BitXor](https://doc.rust-lang.org/stable/std/ops/trait.BitXor.html "trait std::ops::BitXor") The bitwise XOR operator `^`. [BitXorAssign](https://doc.rust-lang.org/stable/std/ops/trait.BitXorAssign.html "trait std::ops::BitXorAssign") The bitwise XOR assignment operator `^=`. [Deref](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") Used for immutable dereferencing operations, like `*v`. [DerefMut](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "trait std::ops::DerefMut") Used for mutable dereferencing operations, like in `*v = 1;`. [Div](https://doc.rust-lang.org/stable/std/ops/trait.Div.html "trait std::ops::Div") The division operator `/`. [DivAssign](https://doc.rust-lang.org/stable/std/ops/trait.DivAssign.html "trait std::ops::DivAssign") The division assignment operator `/=`. [Drop](https://doc.rust-lang.org/stable/std/ops/trait.Drop.html "trait std::ops::Drop") Custom code within the destructor. [Fn](https://doc.rust-lang.org/stable/std/ops/trait.Fn.html "trait std::ops::Fn") The version of the call operator that takes an immutable receiver. [FnMut](https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html "trait std::ops::FnMut") The version of the call operator that takes a mutable receiver. [FnOnce](https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html "trait std::ops::FnOnce") The version of the call operator that takes a by-value receiver. [Index](https://doc.rust-lang.org/stable/std/ops/trait.Index.html "trait std::ops::Index") Used for indexing operations (`container[index]`) in immutable contexts. [IndexMut](https://doc.rust-lang.org/stable/std/ops/trait.IndexMut.html "trait std::ops::IndexMut") Used for indexing operations (`container[index]`) in mutable contexts. [Mul](https://doc.rust-lang.org/stable/std/ops/trait.Mul.html "trait std::ops::Mul") The multiplication operator `*`. [MulAssign](https://doc.rust-lang.org/stable/std/ops/trait.MulAssign.html "trait std::ops::MulAssign") The multiplication assignment operator `*=`. [Neg](https://doc.rust-lang.org/stable/std/ops/trait.Neg.html "trait std::ops::Neg") The unary negation operator `-`. [Not](https://doc.rust-lang.org/stable/std/ops/trait.Not.html "trait std::ops::Not") The unary logical negation operator `!`. [RangeBounds](https://doc.rust-lang.org/stable/std/ops/trait.RangeBounds.html "trait std::ops::RangeBounds") `RangeBounds` is implemented by Rust’s built-in range types, produced by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`. [Rem](https://doc.rust-lang.org/stable/std/ops/trait.Rem.html "trait std::ops::Rem") The remainder operator `%`. [RemAssign](https://doc.rust-lang.org/stable/std/ops/trait.RemAssign.html "trait std::ops::RemAssign") The remainder assignment operator `%=`. [Shl](https://doc.rust-lang.org/stable/std/ops/trait.Shl.html "trait std::ops::Shl") The left shift operator `<<`. Note that because this trait is implemented for all integer types with multiple right-hand-side types, Rust’s type checker has special handling for `_ << _`, setting the result type for integer operations to the type of the left-hand-side operand. This means that though `a << b` and `a.shl(b)` are one and the same from an evaluation standpoint, they are different when it comes to type inference. [ShlAssign](https://doc.rust-lang.org/stable/std/ops/trait.ShlAssign.html "trait std::ops::ShlAssign") The left shift assignment operator `<<=`. [Shr](https://doc.rust-lang.org/stable/std/ops/trait.Shr.html "trait std::ops::Shr") The right shift operator `>>`. Note that because this trait is implemented for all integer types with multiple right-hand-side types, Rust’s type checker has special handling for `_ >> _`, setting the result type for integer operations to the type of the left-hand-side operand. This means that though `a >> b` and `a.shr(b)` are one and the same from an evaluation standpoint, they are different when it comes to type inference. [ShrAssign](https://doc.rust-lang.org/stable/std/ops/trait.ShrAssign.html "trait std::ops::ShrAssign") The right shift assignment operator `>>=`. [Sub](https://doc.rust-lang.org/stable/std/ops/trait.Sub.html "trait std::ops::Sub") The subtraction operator `-`. [SubAssign](https://doc.rust-lang.org/stable/std/ops/trait.SubAssign.html "trait std::ops::SubAssign") The subtraction assignment operator `-=`. [CoerceShared](https://doc.rust-lang.org/stable/std/ops/trait.CoerceShared.html "trait std::ops::CoerceShared") Experimental Allows reborrowable value to be reborrowed as shared, creating a copy that disables the source for writes for the lifetime of the copy. [CoerceUnsized](https://doc.rust-lang.org/stable/std/ops/trait.CoerceUnsized.html "trait std::ops::CoerceUnsized") Experimental Trait that indicates that this is a pointer or a wrapper for one, where unsizing can be performed on the pointee. [Coroutine](https://doc.rust-lang.org/stable/std/ops/trait.Coroutine.html "trait std::ops::Coroutine") Experimental The trait implemented by builtin coroutine types. [DerefPure](https://doc.rust-lang.org/stable/std/ops/trait.DerefPure.html "trait std::ops::DerefPure") Experimental Perma-unstable marker trait. Indicates that the type has a well-behaved [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") (and, if applicable, [`DerefMut`](https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html "trait std::ops::DerefMut") ) implementation. This is relied on for soundness of deref patterns. [DispatchFromDyn](https://doc.rust-lang.org/stable/std/ops/trait.DispatchFromDyn.html "trait std::ops::DispatchFromDyn") Experimental `DispatchFromDyn` is used in the implementation of dyn-compatibility checks (specifically allowing arbitrary self types), to guarantee that a method’s receiver type can be dispatched on. [FromResidual](https://doc.rust-lang.org/stable/std/ops/trait.FromResidual.html "trait std::ops::FromResidual") Experimental Used to specify which residuals can be converted into which [`crate::ops::Try`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") types. [IntoBounds](https://doc.rust-lang.org/stable/std/ops/trait.IntoBounds.html "trait std::ops::IntoBounds") Experimental Used to convert a range into start and end bounds, consuming the range by value. [OneSidedRange](https://doc.rust-lang.org/stable/std/ops/trait.OneSidedRange.html "trait std::ops::OneSidedRange") Experimental `OneSidedRange` is implemented for built-in range types that are unbounded on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`, but `..`, `d..e`, and `f..=g` do not. [Reborrow](https://doc.rust-lang.org/stable/std/ops/trait.Reborrow.html "trait std::ops::Reborrow") Experimental Allows value to be reborrowed as exclusive, creating a copy of the value that disables the source for reads and writes for the lifetime of the copy. [Receiver](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html "trait std::ops::Receiver") Experimental Indicates that a struct can be used as a method receiver. That is, a type can use this type as a type of `self`, like this: [Residual](https://doc.rust-lang.org/stable/std/ops/trait.Residual.html "trait std::ops::Residual") Experimental Allows retrieving the canonical type implementing [`Try`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") that has this type as its residual and allows it to hold an `O` as its output. [Try](https://doc.rust-lang.org/stable/std/ops/trait.Try.html "trait std::ops::Try") Experimental The `?` operator and `try {}` blocks. --- # without_provenance in std::ptr - Rust [without\_provenance](https://doc.rust-lang.org/stable/std/ptr/fn.without_provenance.html#) -------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[ptr](https://doc.rust-lang.org/stable/std/ptr/index.html) Function without\_provenance Copy item path =========================================== 1.84.0 (const: 1.84.0) · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mod.rs.html#883) pub const fn without_provenance(addr: usize) -> *const T Expand description Creates a pointer with the given address and no [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance "mod std::ptr") . This is equivalent to `ptr::null().with_addr(addr)`. Without provenance, this pointer is not associated with any actual allocation. Such a no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are little more than a `usize` address in disguise. This is different from `addr as *const T`, which creates a pointer that picks up a previously exposed provenance. See [`with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html "fn std::ptr::with_exposed_provenance") for more details on that operation. This is a [Strict Provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#strict-provenance "mod std::ptr") API. --- # with_exposed_provenance in std::ptr - Rust [with\_exposed\_provenance](https://doc.rust-lang.org/stable/std/ptr/fn.with_exposed_provenance.html#) ------------------------------------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[ptr](https://doc.rust-lang.org/stable/std/ptr/index.html) Function with\_exposed\_provenance Copy item path ================================================= 1.84.0 (const: 1.91.0) · [Source](https://doc.rust-lang.org/stable/src/core/ptr/mod.rs.html#985) pub const fn with_exposed_provenance(addr: usize) -> *const T Expand description Converts an address back to a pointer, picking up some previously ‘exposed’ [provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#provenance "mod std::ptr") . This is fully equivalent to `addr as *const T`. The provenance of the returned pointer is that of _some_ pointer that was previously exposed by passing it to [`expose_provenance`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.expose_provenance "method pointer::expose_provenance") , or a `ptr as usize` cast. In addition, memory which is outside the control of the Rust abstract machine (MMIO registers, for example) is always considered to be accessible with an exposed provenance, so long as this memory is disjoint from memory that will be used by the abstract machine such as the stack, heap, and statics. The exact provenance that gets picked is not specified. The compiler will do its best to pick the “right” provenance for you (whatever that may be), but currently we cannot provide any guarantees about which provenance the resulting pointer will have – and therefore there is no definite specification for which memory the resulting pointer may access. If there is _no_ previously ‘exposed’ provenance that justifies the way the returned pointer will be used, the program has undefined behavior. In particular, the aliasing rules still apply: pointers and references that have been invalidated due to aliasing accesses cannot be used anymore, even if they have been exposed! Due to its inherent ambiguity, this operation may not be supported by tools that help you to stay conformant with the Rust memory model. It is recommended to use [Strict Provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#strict-provenance "mod std::ptr") APIs such as [`with_addr`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.with_addr "method pointer::with_addr") wherever possible. On most platforms this will produce a value with the same bytes as the address. Platforms which need to store additional information in a pointer may not support this operation, since it is generally not possible to actually _compute_ which provenance the returned pointer has to pick up. This is an [Exposed Provenance](https://doc.rust-lang.org/stable/std/ptr/index.html#exposed-provenance "mod std::ptr") API. --- # Using Structs to Structure Related Data - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") A _struct_, or _structure_, is a custom data type that lets you package together and name multiple related values that make up a meaningful group. If you’re familiar with an object-oriented language, a struct is like an object’s data attributes. In this chapter, we’ll compare and contrast tuples with structs to build on what you already know and demonstrate when structs are a better way to group data. We’ll demonstrate how to define and instantiate structs. We’ll discuss how to define associated functions, especially the kind of associated functions called _methods_, to specify behavior associated with a struct type. Structs and enums (discussed in Chapter 6) are the building blocks for creating new types in your program’s domain to take full advantage of Rust’s compile-time type checking. --- # Hash in std::hash - Rust [Hash](https://doc.rust-lang.org/stable/std/hash/derive.Hash.html#) -------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[hash](https://doc.rust-lang.org/stable/std/hash/index.html) Derive Macro Hash Copy item path ================================ 1.38.0 · [Source](https://doc.rust-lang.org/stable/src/core/hash/mod.rs.html#251) #[derive(Hash)] Expand description Derive macro generating an impl of the trait `Hash`. --- # Tuple types - The Rust Reference Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Reference ================== [](https://doc.rust-lang.org/stable/reference/print.html "Print this book") [](https://github.com/rust-lang/reference/ "Git repository") [](https://github.com/rust-lang/reference/edit/master/src/types/tuple.md "Suggest an edit") [\[type.tuple\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple "type.tuple") [\[type.tuple.syntax\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.syntax "type.tuple.syntax") **Syntax** [TupleType](https://doc.rust-lang.org/stable/reference/types/tuple.html#railroad-TupleType) →       ( )     | ( ( [Type](https://doc.rust-lang.org/stable/reference/types.html#grammar-Type) , )+ [Type](https://doc.rust-lang.org/stable/reference/types.html#grammar-Type) ? ) Show Railroad TupleType ( ) ( Type , Type ) [\[type.tuple.intro\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.intro "type.tuple.intro") _Tuple types_ are a family of structural types[1](https://doc.rust-lang.org/stable/reference/types/tuple.html#footnote-1) for heterogeneous lists of other types. The syntax for a tuple type is a parenthesized, comma-separated list of types. [\[type.tuple.restriction\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.restriction "type.tuple.restriction") 1-ary tuples require a comma after their element type to be disambiguated with a [parenthesized type](https://doc.rust-lang.org/stable/reference/types.html#parenthesized-types) . [\[type.tuple.field-number\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.field-number "type.tuple.field-number") A tuple type has a number of fields equal to the length of the list of types. This number of fields determines the _arity_ of the tuple. A tuple with `n` fields is called an _n-ary tuple_. For example, a tuple with 2 fields is a 2-ary tuple. [\[type.tuple.field-name\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.field-name "type.tuple.field-name") Fields of tuples are named using increasing numeric names matching their position in the list of types. The first field is `0`. The second field is `1`. And so on. The type of each field is the type of the same position in the tuple’s list of types. [\[type.tuple.unit\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.unit "type.tuple.unit") For convenience and historical reasons, the tuple type with no fields (`()`) is often called _unit_ or _the unit type_. Its one value is also called _unit_ or _the unit value_. Some examples of tuple types: * `()` (unit) * `(i32,)` (1-ary tuple) * `(f64, f64)` * `(String, i32)` * `(i32, String)` (different type from the previous example) * `(i32, f64, Vec, Option)` [\[type.tuple.constructor\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.constructor "type.tuple.constructor") Values of this type are constructed using a [tuple expression](https://doc.rust-lang.org/stable/reference/expressions/tuple-expr.html#tuple-expressions) . Furthermore, various expressions will produce the unit value if there is no other meaningful value for it to evaluate to. [\[type.tuple.access\]](https://doc.rust-lang.org/stable/reference/types/tuple.html#r-type.tuple.access "type.tuple.access") Tuple fields can be accessed by either a [tuple index expression](https://doc.rust-lang.org/stable/reference/expressions/tuple-expr.html#tuple-indexing-expressions) or [pattern matching](https://doc.rust-lang.org/stable/reference/patterns.html#tuple-patterns) . * * * 1. Structural types are always equivalent if their internal types are equivalent. For a nominal version of tuples, see [tuple structs](https://doc.rust-lang.org/stable/reference/types/struct.html) . [↩](https://doc.rust-lang.org/stable/reference/types/tuple.html#fr-1-1) --- # Textual types - The Rust Reference Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Reference ================== [](https://doc.rust-lang.org/stable/reference/print.html "Print this book") [](https://github.com/rust-lang/reference/ "Git repository") [](https://github.com/rust-lang/reference/edit/master/src/types/textual.md "Suggest an edit") [\[type.text\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text "type.text") [\[type.text.intro\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text.intro "type.text.intro") The types `char` and `str` hold textual data. [\[type.text.char-value\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text.char-value "type.text.char-value") A value of type `char` is a [Unicode scalar value](http://www.unicode.org/glossary/#unicode_scalar_value) (i.e. a code point that is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000 to 0x10FFFF range. [\[type.text.char-precondition\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text.char-precondition "type.text.char-precondition") It is immediate [undefined behavior](https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html) to create a `char` that falls outside this range. A `[char]` is effectively a UCS-4 / UTF-32 string of length 1. [\[type.text.str-value\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text.str-value "type.text.str-value") A value of type `str` is represented the same way as `[u8]`, a slice of 8-bit unsigned bytes. However, the Rust standard library makes extra assumptions about `str`: methods working on `str` assume and ensure that the data in there is valid UTF-8. Calling a `str` method with a non-UTF-8 buffer can cause [undefined behavior](https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html) now or in the future. [\[type.text.str-unsized\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text.str-unsized "type.text.str-unsized") Since `str` is a [dynamically sized type](https://doc.rust-lang.org/stable/reference/dynamically-sized-types.html) , it can only be instantiated through a pointer type, such as `&str`. The layout of `&str` is the same as the layout of `&[u8]`. [\[type.text.layout\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.text.layout "type.text.layout") [\[type.layout.char-layout\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.layout.char-layout "type.layout.char-layout") `char` is guaranteed to have the same size and alignment as `u32` on all platforms. [\[type.layout.char-validity\]](https://doc.rust-lang.org/stable/reference/types/textual.html#r-type.layout.char-validity "type.layout.char-validity") Every byte of a `char` is guaranteed to be initialized (in other words, `transmute::()]>(...)` is always sound – but since some bit patterns are invalid `char`s, the inverse is not always sound). --- # An Example Program Using Structs - The Rust Programming Language Keyboard shortcuts ------------------ Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help * Auto * Light * Rust * Coal * Navy * Ayu The Rust Programming Language ============================= [](https://doc.rust-lang.org/stable/book/print.html "Print this book") [](https://github.com/rust-lang/book "Git repository") To understand when we might want to use structs, let’s write a program that calculates the area of a rectangle. We’ll start by using single variables and then refactor the program until we’re using structs instead. Let’s make a new binary project with Cargo called _rectangles_ that will take the width and height of a rectangle specified in pixels and calculate the area of the rectangle. Listing 5-8 shows a short program with one way of doing exactly that in our project’s _src/main.rs_. Filename: src/main.rs fn main() { let width1 = 30; let height1 = 50; println!( "The area of the rectangle is {} square pixels.", area(width1, height1) ); } fn area(width: u32, height: u32) -> u32 { width * height } [Listing 5-8](https://doc.rust-lang.org/stable/book/ch05-02-example-structs.html#listing-5-8) : Calculating the area of a rectangle specified by separate width and height variables Now, run this program using `cargo run`: $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s Running `target/debug/rectangles` The area of the rectangle is 1500 square pixels. This code succeeds in figuring out the area of the rectangle by calling the `area` function with each dimension, but we can do more to make this code clear and readable. The issue with this code is evident in the signature of `area`: fn main() { let width1 = 30; let height1 = 50; println!( "The area of the rectangle is {} square pixels.", area(width1, height1) ); } fn area(width: u32, height: u32) -> u32 { width * height } The `area` function is supposed to calculate the area of one rectangle, but the function we wrote has two parameters, and it’s not clear anywhere in our program that the parameters are related. It would be more readable and more manageable to group width and height together. We’ve already discussed one way we might do that in [“The Tuple Type”](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html#the-tuple-type) section of Chapter 3: by using tuples. Listing 5-9 shows another version of our program that uses tuples. Filename: src/main.rs fn main() { let rect1 = (30, 50); println!( "The area of the rectangle is {} square pixels.", area(rect1) ); } fn area(dimensions: (u32, u32)) -> u32 { dimensions.0 * dimensions.1 } [Listing 5-9](https://doc.rust-lang.org/stable/book/ch05-02-example-structs.html#listing-5-9) : Specifying the width and height of the rectangle with a tuple In one way, this program is better. Tuples let us add a bit of structure, and we’re now passing just one argument. But in another way, this version is less clear: Tuples don’t name their elements, so we have to index into the parts of the tuple, making our calculation less obvious. Mixing up the width and height wouldn’t matter for the area calculation, but if we want to draw the rectangle on the screen, it would matter! We would have to keep in mind that `width` is the tuple index `0` and `height` is the tuple index `1`. This would be even harder for someone else to figure out and keep in mind if they were to use our code. Because we haven’t conveyed the meaning of our data in our code, it’s now easier to introduce errors. We use structs to add meaning by labeling the data. We can transform the tuple we’re using into a struct with a name for the whole as well as names for the parts, as shown in Listing 5-10. Filename: src/main.rs struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!( "The area of the rectangle is {} square pixels.", area(&rect1) ); } fn area(rectangle: &Rectangle) -> u32 { rectangle.width * rectangle.height } [Listing 5-10](https://doc.rust-lang.org/stable/book/ch05-02-example-structs.html#listing-5-10) : Defining a `Rectangle` struct Here, we’ve defined a struct and named it `Rectangle`. Inside the curly brackets, we defined the fields as `width` and `height`, both of which have type `u32`. Then, in `main`, we created a particular instance of `Rectangle` that has a width of `30` and a height of `50`. Our `area` function is now defined with one parameter, which we’ve named `rectangle`, whose type is an immutable borrow of a struct `Rectangle` instance. As mentioned in Chapter 4, we want to borrow the struct rather than take ownership of it. This way, `main` retains its ownership and can continue using `rect1`, which is the reason we use the `&` in the function signature and where we call the function. The `area` function accesses the `width` and `height` fields of the `Rectangle` instance (note that accessing fields of a borrowed struct instance does not move the field values, which is why you often see borrows of structs). Our function signature for `area` now says exactly what we mean: Calculate the area of `Rectangle`, using its `width` and `height` fields. This conveys that the width and height are related to each other, and it gives descriptive names to the values rather than using the tuple index values of `0` and `1`. This is a win for clarity. It’d be useful to be able to print an instance of `Rectangle` while we’re debugging our program and see the values for all its fields. Listing 5-11 tries using the [`println!` macro](https://doc.rust-lang.org/stable/std/macro.println.html) as we have used in previous chapters. This won’t work, however. Filename: src/main.rs struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {rect1}"); } [Listing 5-11](https://doc.rust-lang.org/stable/book/ch05-02-example-structs.html#listing-5-11) : Attempting to print a `Rectangle` instance When we compile this code, we get an error with this core message: error[E0277]: `Rectangle` doesn't implement `std::fmt::Display` The `println!` macro can do many kinds of formatting, and by default, the curly brackets tell `println!` to use formatting known as `Display`: output intended for direct end user consumption. The primitive types we’ve seen so far implement `Display` by default because there’s only one way you’d want to show a `1` or any other primitive type to a user. But with structs, the way `println!` should format the output is less clear because there are more display possibilities: Do you want commas or not? Do you want to print the curly brackets? Should all the fields be shown? Due to this ambiguity, Rust doesn’t try to guess what we want, and structs don’t have a provided implementation of `Display` to use with `println!` and the `{}` placeholder. If we continue reading the errors, we’ll find this helpful note: = help: the trait `std::fmt::Display` is not implemented for `Rectangle` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead Let’s try it! The `println!` macro call will now look like `println!("rect1 is {rect1:?}");`. Putting the specifier `:?` inside the curly brackets tells `println!` we want to use an output format called `Debug`. The `Debug` trait enables us to print our struct in a way that is useful for developers so that we can see its value while we’re debugging our code. Compile the code with this change. Drat! We still get an error: error[E0277]: `Rectangle` doesn't implement `Debug` But again, the compiler gives us a helpful note: = help: the trait `Debug` is not implemented for `Rectangle` = note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle` Rust _does_ include functionality to print out debugging information, but we have to explicitly opt in to make that functionality available for our struct. To do that, we add the outer attribute `#[derive(Debug)]` just before the struct definition, as shown in Listing 5-12. Filename: src/main.rs #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {rect1:?}"); } [Listing 5-12](https://doc.rust-lang.org/stable/book/ch05-02-example-structs.html#listing-5-12) : Adding the attribute to derive the `Debug` trait and printing the `Rectangle` instance using debug formatting Now when we run the program, we won’t get any errors, and we’ll see the following output: $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s Running `target/debug/rectangles` rect1 is Rectangle { width: 30, height: 50 } Nice! It’s not the prettiest output, but it shows the values of all the fields for this instance, which would definitely help during debugging. When we have larger structs, it’s useful to have output that’s a bit easier to read; in those cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. In this example, using the `{:#?}` style will output the following: $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s Running `target/debug/rectangles` rect1 is Rectangle { width: 30, height: 50, } Another way to print out a value using the `Debug` format is to use the [`dbg!` macro](https://doc.rust-lang.org/stable/std/macro.dbg.html) , which takes ownership of an expression (as opposed to `println!`, which takes a reference), prints the file and line number of where that `dbg!` macro call occurs in your code along with the resultant value of that expression, and returns ownership of the value. Note: Calling the `dbg!` macro prints to the standard error console stream (`stderr`), as opposed to `println!`, which prints to the standard output console stream (`stdout`). We’ll talk more about `stderr` and `stdout` in the [“Redirecting Errors to Standard Error” section in Chapter 12](https://doc.rust-lang.org/stable/book/ch12-06-writing-to-stderr-instead-of-stdout.html) . Here’s an example where we’re interested in the value that gets assigned to the `width` field, as well as the value of the whole struct in `rect1`: #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let scale = 2; let rect1 = Rectangle { width: dbg!(30 * scale), height: 50, }; dbg!(&rect1); } We can put `dbg!` around the expression `30 * scale` and, because `dbg!` returns ownership of the expression’s value, the `width` field will get the same value as if we didn’t have the `dbg!` call there. We don’t want `dbg!` to take ownership of `rect1`, so we use a reference to `rect1` in the next call. Here’s what the output of this example looks like: $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s Running `target/debug/rectangles` [src/main.rs:10:16] 30 * scale = 60 [src/main.rs:14:5] &rect1 = Rectangle { width: 60, height: 50, } We can see the first bit of output came from _src/main.rs_ line 10 where we’re debugging the expression `30 * scale`, and its resultant value is `60` (the `Debug` formatting implemented for integers is to print only their value). The `dbg!` call on line 14 of _src/main.rs_ outputs the value of `&rect1`, which is the `Rectangle` struct. This output uses the pretty `Debug` formatting of the `Rectangle` type. The `dbg!` macro can be really helpful when you’re trying to figure out what your code is doing! In addition to the `Debug` trait, Rust has provided a number of traits for us to use with the `derive` attribute that can add useful behavior to our custom types. Those traits and their behaviors are listed in [Appendix C](https://doc.rust-lang.org/stable/book/appendix-03-derivable-traits.html) . We’ll cover how to implement these traits with custom behavior as well as how to create your own traits in Chapter 10. There are also many attributes other than `derive`; for more information, see [the “Attributes” section of the Rust Reference](https://doc.rust-lang.org/stable/reference/attributes.html) . Our `area` function is very specific: It only computes the area of rectangles. It would be helpful to tie this behavior more closely to our `Rectangle` struct because it won’t work with any other type. Let’s look at how we can continue to refactor this code by turning the `area` function into an `area` method defined on our `Rectangle` type. --- # Allocator in std::alloc - Rust [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#) ------------------------------------------------------------------------------ [std](https://doc.rust-lang.org/stable/std/index.html) ::[alloc](https://doc.rust-lang.org/stable/std/alloc/index.html) Trait Allocator Copy item path ============================== [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#105) pub unsafe trait Allocator { // Required methods fn allocate(&self, layout: Layout) -> Result, AllocError>; unsafe fn deallocate(&self, ptr: NonNull, layout: Layout); // Provided methods fn allocate_zeroed( &self, layout: Layout, ) -> Result, AllocError> { ... } unsafe fn grow( &self, ptr: NonNull, old_layout: Layout, new_layout: Layout, ) -> Result, AllocError> { ... } unsafe fn grow_zeroed( &self, ptr: NonNull, old_layout: Layout, new_layout: Layout, ) -> Result, AllocError> { ... } unsafe fn shrink( &self, ptr: NonNull, old_layout: Layout, new_layout: Layout, ) -> Result, AllocError> { ... } fn by_ref(&self) -> &Self where Self: Sized { ... } } 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Expand description An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of data described via [`Layout`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") . `Allocator` is designed to be implemented on ZSTs, references, or smart pointers. An allocator for `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the allocated memory. In contrast to [`GlobalAlloc`](https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html "trait std::alloc::GlobalAlloc") , `Allocator` allows zero-sized allocations. If an underlying allocator does not support this (like jemalloc) or responds by returning a null pointer (such as `libc::malloc`), this must be caught by the implementation. #### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) Currently allocated memory Some of the methods require that a memory block is _currently allocated_ by an allocator. This means that: * the starting address for that memory block was previously returned by [`allocate`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#tymethod.allocate "method std::alloc::Allocator::allocate") , [`grow`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.grow "method std::alloc::Allocator::grow") , or [`shrink`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.shrink "method std::alloc::Allocator::shrink") , and * the memory block has not subsequently been deallocated. A memory block is deallocated by a call to [`deallocate`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#tymethod.deallocate "method std::alloc::Allocator::deallocate") , or by a call to [`grow`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.grow "method std::alloc::Allocator::grow") or [`shrink`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.shrink "method std::alloc::Allocator::shrink") that returns `Ok`. A call to `grow` or `shrink` that returns `Err`, does not deallocate the memory block passed to it. #### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#memory-fitting) Memory fitting Some of the methods require that a `layout` _fit_ a memory block or vice versa. This means that the following conditions must hold: * the memory block must be _currently allocated_ with alignment of [`layout.align()`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.align "method std::alloc::Layout::align") , and * [`layout.size()`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.size "method std::alloc::Layout::size") must fall in the range `min ..= max`, where: * `min` is the size of the layout used to allocate the block, and * `max` is the actual size returned from [`allocate`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#tymethod.allocate "method std::alloc::Allocator::allocate") , [`grow`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.grow "method std::alloc::Allocator::grow") , or [`shrink`](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.shrink "method std::alloc::Allocator::shrink") . [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#safety) Safety ---------------------------------------------------------------------------------- Memory blocks that are [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) by an allocator, must point to valid memory, and retain their validity until either: * the memory block is deallocated, or * the allocator is dropped. Copying, cloning, or moving the allocator must not invalidate memory blocks returned from it. A copied or cloned allocator must behave like the original allocator. A memory block which is [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) may be passed to any method of the allocator that accepts such an argument. Required Methods[§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#required-methods) ------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#132) #### fn [allocate](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#tymethod.allocate) (&self, layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>, [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") \> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Attempts to allocate a block of memory. On success, returns a [`NonNull<[u8]>`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") meeting the size and alignment guarantees of `layout`. The returned block may have a larger size than specified by `layout.size()`, and may or may not have its contents initialized. The returned block of memory remains valid as long as it is [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) and the shorter of: * the borrow-checker lifetime of the allocator type itself. * as long as the allocator and all its clones have not been dropped. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#errors) Errors Returning `Err` indicates that either memory is exhausted or `layout` does not meet allocator’s size or alignment constraints. Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or aborting, but this is not a strict requirement. (Specifically: it is _legal_ to implement this trait atop an underlying native allocation library that aborts on memory exhaustion.) Clients wishing to abort computation in response to an allocation error are encouraged to call the [`handle_alloc_error`](https://doc.rust-lang.org/stable/alloc/alloc/fn.handle_alloc_error.html) function, rather than directly invoking `panic!` or similar. [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#165) #### unsafe fn [deallocate](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#tymethod.deallocate) (&self, ptr: [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) \>, layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") ) 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Deallocates the memory referenced by `ptr`. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#safety-1) Safety * `ptr` must denote a block of memory [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) via this allocator, and * `layout` must [_fit_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#memory-fitting) that block of memory. Provided Methods[§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#provided-methods) ------------------------------------------------------------------------------------------------------ [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#149) #### fn [allocate\_zeroed](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.allocate_zeroed) (&self, layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>, [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") \> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Behaves like `allocate`, but also ensures that the returned memory is zero-initialized. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#errors-1) Errors Returning `Err` indicates that either memory is exhausted or `layout` does not meet allocator’s size or alignment constraints. Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or aborting, but this is not a strict requirement. (Specifically: it is _legal_ to implement this trait atop an underlying native allocation library that aborts on memory exhaustion.) Clients wishing to abort computation in response to an allocation error are encouraged to call the [`handle_alloc_error`](https://doc.rust-lang.org/stable/alloc/alloc/fn.handle_alloc_error.html) function, rather than directly invoking `panic!` or similar. [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#205-210) #### unsafe fn [grow](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.grow) ( &self, ptr: [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) \>, old\_layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") , new\_layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") , ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>, [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") \> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Attempts to extend the memory block. Returns a new [`NonNull<[u8]>`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") containing a pointer and the actual size of the allocated memory. The pointer is suitable for holding data described by `new_layout`. To accomplish this, the allocator may extend the allocation referenced by `ptr` to fit the new layout. If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the allocation was grown in-place. The newly returned pointer is the only valid pointer for accessing this memory now. If this method returns `Err`, then ownership of the memory block has not been transferred to this allocator, and the contents of the memory block are unaltered. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#safety-2) Safety * `ptr` must denote a block of memory [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) via this allocator. * `old_layout` must [_fit_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#memory-fitting) that block of memory (The `new_layout` argument need not fit it.). * `new_layout.size()` must be greater than or equal to `old_layout.size()`. Note that `new_layout.align()` need not be the same as `old_layout.align()`. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#errors-2) Errors Returns `Err` if the new layout does not meet the allocator’s size and alignment constraints of the allocator, or if growing otherwise fails. Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or aborting, but this is not a strict requirement. (Specifically: it is _legal_ to implement this trait atop an underlying native allocation library that aborts on memory exhaustion.) Clients wishing to abort computation in response to an allocation error are encouraged to call the [`handle_alloc_error`](https://doc.rust-lang.org/stable/alloc/alloc/fn.handle_alloc_error.html) function, rather than directly invoking `panic!` or similar. [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#268-273) #### unsafe fn [grow\_zeroed](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.grow_zeroed) ( &self, ptr: [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) \>, old\_layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") , new\_layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") , ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>, [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") \> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Behaves like `grow`, but also ensures that the new contents are set to zero before being returned. The memory block will contain the following contents after a successful call to `grow_zeroed`: * Bytes `0..old_layout.size()` are preserved from the original allocation. * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on the allocator implementation. `old_size` refers to the size of the memory block prior to the `grow_zeroed` call, which may be larger than the size that was originally requested when it was allocated. * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory block returned by the `grow_zeroed` call. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#safety-3) Safety * `ptr` must denote a block of memory [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) via this allocator. * `old_layout` must [_fit_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#memory-fitting) that block of memory (The `new_layout` argument need not fit it.). * `new_layout.size()` must be greater than or equal to `old_layout.size()`. Note that `new_layout.align()` need not be the same as `old_layout.align()`. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#errors-3) Errors Returns `Err` if the new layout does not meet the allocator’s size and alignment constraints of the allocator, or if growing otherwise fails. Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or aborting, but this is not a strict requirement. (Specifically: it is _legal_ to implement this trait atop an underlying native allocation library that aborts on memory exhaustion.) Clients wishing to abort computation in response to an allocation error are encouraged to call the [`handle_alloc_error`](https://doc.rust-lang.org/stable/alloc/alloc/fn.handle_alloc_error.html) function, rather than directly invoking `panic!` or similar. [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#332-337) #### unsafe fn [shrink](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.shrink) ( &self, ptr: [NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html) \>, old\_layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") , new\_layout: [Layout](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html "struct std::alloc::Layout") , ) -> [Result](https://doc.rust-lang.org/stable/std/result/enum.Result.html "enum std::result::Result") <[NonNull](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") <\[[u8](https://doc.rust-lang.org/stable/std/primitive.u8.html)\ \]>, [AllocError](https://doc.rust-lang.org/stable/std/alloc/struct.AllocError.html "struct std::alloc::AllocError") \> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Attempts to shrink the memory block. Returns a new [`NonNull<[u8]>`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html "struct std::ptr::NonNull") containing a pointer and the actual size of the allocated memory. The pointer is suitable for holding data described by `new_layout`. To accomplish this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout. If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the allocation was shrunk in-place. The newly returned pointer is the only valid pointer for accessing this memory now. If this method returns `Err`, then ownership of the memory block has not been transferred to this allocator, and the contents of the memory block are unaltered. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#safety-4) Safety * `ptr` must denote a block of memory [_currently allocated_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#currently-allocated-memory) via this allocator. * `old_layout` must [_fit_](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#memory-fitting) that block of memory (The `new_layout` argument need not fit it.). * `new_layout.size()` must be smaller than or equal to `old_layout.size()`. Note that `new_layout.align()` need not be the same as `old_layout.align()`. ##### [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#errors-4) Errors Returns `Err` if the new layout does not meet the allocator’s size and alignment constraints of the allocator, or if shrinking otherwise fails. Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or aborting, but this is not a strict requirement. (Specifically: it is _legal_ to implement this trait atop an underlying native allocation library that aborts on memory exhaustion.) Clients wishing to abort computation in response to an allocation error are encouraged to call the [`handle_alloc_error`](https://doc.rust-lang.org/stable/alloc/alloc/fn.handle_alloc_error.html) function, rather than directly invoking `panic!` or similar. [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#362-364) #### fn [by\_ref](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#method.by_ref) (&self) -> &Self where Self: [Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838) ) Creates a “by reference” adapter for this instance of `Allocator`. The returned adapter also implements `Allocator` and will simply borrow this. Implementors[§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#implementors) ---------------------------------------------------------------------------------------------- [Source](https://doc.rust-lang.org/stable/src/alloc/alloc.rs.html#247) [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#impl-Allocator-for-Global) ### impl [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") for [Global](https://doc.rust-lang.org/stable/std/alloc/struct.Global.html "struct std::alloc::Global") [Source](https://doc.rust-lang.org/stable/src/std/alloc.rs.html#204-288) [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#impl-Allocator-for-System) ### impl [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") for [System](https://doc.rust-lang.org/stable/std/alloc/struct.System.html "struct std::alloc::System") [Source](https://doc.rust-lang.org/stable/src/core/alloc/mod.rs.html#371-373) [§](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html#impl-Allocator-for-%26A) ### impl [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") for [&A](https://doc.rust-lang.org/stable/std/primitive.reference.html) where A: [Allocator](https://doc.rust-lang.org/stable/std/alloc/trait.Allocator.html "trait std::alloc::Allocator") + ?[Sized](https://doc.rust-lang.org/stable/std/marker/trait.Sized.html "trait std::marker::Sized") , --- # Redirection Redirecting to [../../../core/arch/x86/struct.\_\_m128h.html](https://doc.rust-lang.org/stable/core/arch/x86/struct.__m128h.html) ... --- # Receiver in std::ops - Rust [Receiver](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html#) -------------------------------------------------------------------------- [std](https://doc.rust-lang.org/stable/std/index.html) ::[ops](https://doc.rust-lang.org/stable/std/ops/index.html) Trait Receiver Copy item path ============================= [Source](https://doc.rust-lang.org/stable/src/core/ops/deref.rs.html#369) pub trait Receiver { type Target: ?Sized; } 🔬This is a nightly-only experimental API. (`arbitrary_self_types` [#44874](https://github.com/rust-lang/rust/issues/44874) ) Expand description Indicates that a struct can be used as a method receiver. That is, a type can use this type as a type of `self`, like this: [ⓘ](https://doc.rust-lang.org/stable/std/ops/trait.Receiver.html# "This example deliberately fails to compile") use std::ops::Receiver; struct SmartPointer(T); impl Receiver for SmartPointer { type Target = T; } struct MyContainedType; impl MyContainedType { fn method(self: SmartPointer) { // ... } } fn main() { let ptr = SmartPointer(MyContainedType); ptr.method(); } [](https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0A//+This+is+currently+compile_fail+because+the+compiler-side+parts%0A//+of+arbitrary_self_types+are+not+implemented%0Ause+std::ops::Receiver;%0A%0Astruct+SmartPointer%3CT%3E(T);%0A%0Aimpl%3CT%3E+Receiver+for+SmartPointer%3CT%3E+%7B%0A+++type+Target+=+T;%0A%7D%0A%0Astruct+MyContainedType;%0A%0Aimpl+MyContainedType+%7B%0A++fn+method(self:+SmartPointer%3CSelf%3E)+%7B%0A++++//+...%0A++%7D%0A%7D%0A%0Afn+main()+%7B%0A++let+ptr+=+SmartPointer(MyContainedType);%0A++ptr.method();%0A%7D&edition=2024 "Run code") This trait is blanket implemented for any type which implements [`Deref`](https://doc.rust-lang.org/stable/std/ops/trait.Deref.html "trait std::ops::Deref") , which includes stdlib pointer types like `Box`,`Rc`, `&T`, and `Pin